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

Hi, I'm Jesse Skinner. I'm a web development coach & consultant. I teach web development teams how to scale up their server infrastructure, improve automated testing and monitoring, reduce costs, and modernize their legacy systems. I focus on empowering teams through customized training and coaching.

Feel free to email me. I'm eager to hear about your challenges and see how I can make your life easier.