jQuery Multiple Events Without Default Behaviour

Sometimes you trip over the little things.

With several people working on the same page while we were recreating some JS functionality from scratch I’ve noticed one of my buttons suddenly stopped working. Scratched my head a bit, and for a minute thought that maybe it’s not having a “return false;” in my jQuery live() event handler.

Turned out though that it was actually one of the other developers actually putting a “return false;” in their event handler that just happened to target the same element…

Ideally we needed to propagate the event through a variable number of events but prevent the default behaviour of a link kicking in. preventDefault() to the rescue! :)

$('#tag').live('click', function(event){
    (...)
    event.preventDefault();
});

Now, before blindly applying this piece of code I’d encourage everyone to first read up on why “return false;” is evil. ;)

And for a quick reference here’s a table featured on a related StackOverflow question:

 stop propagationprevent default actionprevent “same element” event handlers
return falseXX 
preventDefault X 
stopPropagationX  
stopImmediatePropagationX X