Prevent jQuery events from firing multiple times

Everyone who are using jQuery will know that sometimes the jQuery events(click, bind, live, on etc ) may fire more than once due to event bubbling.

jquery-events
jquery-events

For example, consider the following code snippet :

$(document).on("click", ".button", function (e) {
    alert("Clicked");
});

Due to event bubbling, a single click on the .button can trigger the click function multiple times. A detailed explanation regarding Event Bubbling and Capturing is provided on the link.

The above problem can be easily resolved by handling the event as follows :

$(document).on("click", ".button", function (e) {
    e.preventDefault();
    if (e.handled !== true) { //Checking for the event whether it has occurred or not.
        e.handled = true; // Basically setting value that the current event has occurred.
        alert("Clicked");
    }
});

However the above solution wont stop event binding process, it will just prevent multiple jQuery events from executing.

Cheers.

12 Comments on "Prevent jQuery events from firing multiple times"


  1. AWESOME!!! Thank You. This took forever to find.

    This helped a ton. Couldn’t find this anywhere else in Google Searches.
    if (e.handled !== true) { //Checking for the event whether it has occurred or not.
    e.handled = true;

    Reply

Leave a Reply

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