JavaScript
Article

Stop jQuery Event Functions

By Sam Deering

A simple way of how to stop a jQuery or JavaScript function in it’s tracks is to use the return false line. In most cases this is not the best way and there are other functions which should be used.

Also see: stop jQuery Event Functions

Return False Example

Simple use the return false line to stop the function and return control to the calling function or page element. This jQuery function toggles the hiding and displaying of #htmlelement and then prevent browser from visiting the href element of the clicked hyperlink

$("a.toggle").click(function () {
    $("#htmlelement").toggle(); // hide/show toggle
    return false; // Prevent browser from visiting the href
});

Other variations to consider:

  • return false;
  • preventDefault()
  • stopPropagation()
  • stopImmediatePropagation()

Which method should you use?

return false;

Use only when the other options are not applicable or when your unsure or desperate.

preventDefault()

Use when you need to cancel the default behavior of say a hyperlink, keyboard shortcut or event etc… It also requires you allow for the event parameter to be accessed in your callback (In this example, I use e):

$("a").click(function (e) {
    // e == our event data
    e.preventDefault();
});

stopPropagation()

This can be used if you have an exception to the rule you specified for an container element with child elements. For example say you have disable hyperlinks on you web page except links in a particular area.

$("a").click(function () {
   // Do nothing
});

$("#dohyperlinksdiv a").click(function (e) {
    // Don't cancel the browser's default action
    // and don't bubble this event!
    e.stopPropagation();
});


stopImmediatePropagation()

Nice function to stop all future bound events. The events will fire in the order they were bound and when it hits the stopImmediatePropagation() function all further bound events are no fired.

$("div a").click(function () {
   // Do something
});

$("div a").click(function (e) {
   // Do something else
   e.stopImmediatePropagation();
});

$("div a").click(function () {
   // THIS NEVER FIRES
});

$("div").click(function () {
   // THIS NEVER FIRES
});

Conclusion

Don’t use return false unless you really have to as it provides poor cancellation and remember to prevent the default actions of elements before you exit the function. Let’s keep our coding nice and neat!

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • Peter

    event.stopImmediatePropagation() worked for me, finally.
    Thank you :)

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.