Coding with Jesse

onAfterClick

March 10th, 2006

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.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!