Tag Archives: javacript

How to cancel events in JavaScript

If you’re writing client-heavy interactive JavaScript applications you’ll have to deal with events a lot. Most people who have come this far will have learned that you can return false at the end of an event to cancel it. But this is not the best way to go about it.

Sample code:

function my_onclick (event) {
	do_some_processing();
	return false;
}

The largest downside is: if an Error occurs in your event handler, the function will not return but throw an Error instead. This means your event is not cancelled. This is particularly embarrassing if the default action is something that you don’t want to have happen, such a submit on a form with an invalid action. You could surround your code with a try-catch statement but since there is a better solution, let’s not get into that.

Another disadvantage is that return false is not equivalent to event.preventDefault(). It also triggers event.stopPropagation(). Most of the time you only need event.preventDefault(). It’s worth noting that some event related features can not be built if you don’t distinguish between these two (see below).

So how do you do it?

Well, you call the right function for the right job. You can use event.preventDefault() to cancel the default behaviour. Prevent a page change when you click on a link. Prevent a submit on a form (AJAX anyone?). Prevent a focus on an input. Prevent a check on a checkbox.

You can use event.stopPropagation() to trap events; to prevent them from going up the DOM-tree. For instance: if you have a tooltip that you want to close when you click anywhere on the page, except not when you click on the tooltip itself. Add an onclick handler that does an event.stopPropagation() on the element that contains the tooltip and you’re done. This doesn’t break any functionality. Links still work in the tooltip, and other things with click events such as input elements. I bet you didn’t think it was that simple huh? Well, it is. This is why events are awesome.

Where did this come from? Why aren’t people just calling the right function? Honestly this isn’t so complex.

I think this might stem from a browser incompatibility. Internet Explorer has event.cancelBubble where other browers use event.stopPropagation. return false works in all browsers.