Coding with Jesse

onAfterClick

Okay, some time ago I posted onAfterPaste, a way to run some code after pasting. You can actually do the same thing with any event. Let's say you want to put an onclick handler on a submit button, but you don't want the function to execute until after the form is submitted. You may want to close the window after launching a new window or submitting a form, but putting window.close() in the onclick would prevent the form from being submitted. Then, do this:

function onAfterClick (e) {
     window.close();
}

var submit= document.getElementById('submit');
submit.onclick = function(e) {
     setTimeout(function() {
          onAfterClick(e);
     }, 1);
}

That's it. It's like the browser processes the click handler, then goes and does it's default click behaviour, then executes the timeout function. So it's almost a kind of magic.. but not really. Anyway, setTimeout is a great tool for making things happen at the right time.

Published on March 10th, 2006. © Jesse Skinner

About the author

Jesse Skinner

I'm Jesse Skinner. I'm a self-employed web developer. I love writing code, and writing about writing code. Sometimes I make videos too. Feel free to email me if you have any questions or comments, or just want to share your story or something you're excited about.