Avoid return false in jQuery Click Bindings

If you’ve ever written any jQuery code to bind to a click event, you’ve likely written something of the form:

[javascript]

$("a.special").click(function(){
// do stuff
return false;
});

[/javascript]

OR

[javascript]

$("a.special").bind("click", function(){
// do stuff
return false;
});

[/javascript]

In these cases, the click event fires and causes the function to do some stuff. The return false prevents the normal behavior of the anchor, i.e. the href attribute is never executed (new URL, hash, etc.). This might appear to be fine on the front-end, but the return false breaks the bubbling of additional click events. This means if there are any other click bindings, after this function gets called, those others do not. Consider this example:

[javascript]

$("a.modal").click(function(){
openModal( $(this).attr("href") );
return false;
});

$("a").click() {
trackCustomAnalytics("click", $(this).attr("href"));
}

[/javascript]

If the first function above fires first, the return false prevents the generic all-anchors analytics function from firing. This is easily preventable by avoiding return false. But you might think “how do I prevent the href on the anchor from executing?” You can use the preventDefault() method of the event to handle this. The appropriate updated code to do such a thing would look like this:

[javascript]

$("a.modal").click(function(e){
e.preventDefault();
openModal( $(this).attr("href") );
});

$("a").click(e) {
e.preventDefault();
trackCustomAnalytics("click", $(this).attr("href"));
}

[/javascript]

As you can see, each function has a parameter passed in, the event object. You can call preventDefault() on this parameter and it will prevent the default behavior of the event, which in the case of a click is the execution of the href attribute.

Read More

Read more about event.preventDefault()

jQuery Live() Method and Event Bubbling

 

Mark Ursino

Mark is Sr. Director at Rightpoint and a Sitecore MVP.

 

3 thoughts on “Avoid return false in jQuery Click Bindings

Leave a Reply to Daniel Cancel reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.