JasonDavis
JasonDavis

Reputation: 48933

JavaScript button click even is firing multiple times per click

I have a JavaScript/jQuery application in which a Bootstrap Modal window is opened when any of the order cards in the image below are clicked on.

In the Modal HTML, I have a Start Timer Button

This timer button is added to the DOM after the DOM has already been loaded. SO I use this code below to attach a click event to the button after DOM loaded...

// Handle Timer Start Button click event
$(document).on('click', '.start-job-btn', function(e) {

    console.log('start timer');
    alert('start timer');

    e.preventDefault(); // prevents default
    return false;

});

HTML

<a href="#" data-order-id="5508" data-order-item-id="158" class="btn btn-primary start-job-btn">Start Job</a>

The Problem

When I click the start button I get my alert and console logger ran 3-6 times each button click!

I cannot figure out why this would happen as it doesn't happen in any other sections of the app. Just this button which has the code shown above.

It's hard to setup a demo app as the project is over 10k lines and would be hard to get it all up but based on this info does anyone have any ideas?


enter image description here

enter image description here

Upvotes: 0

Views: 1215

Answers (2)

taxicala
taxicala

Reputation: 21759

As per your latest comment, i see two possible solutions here. first, put your previous code only in the page that will load the modals. There is no need to bind the event with every call. You will be binding a new function to the same event each time you open a modal.

And you mentioned jquery off method, that would also work:

$(document).off('click', '.start-job-btn');
$(document).on('click', '.start-job-btn', function(e) {
    console.log('start timer');
    alert('start timer');
    e.preventDefault(); // prevents default
    return false;
});

Upvotes: 1

Barmar
Barmar

Reputation: 780871

You're running the code every time you create a modal, so all the buttons are getting multiple click handlers -- one for each modal.

You should either take that code out of the code that creates modals, so you only run it once. Or you should change it so that it only binds to the buttons in that modal:

this_modal.on("click", ".start-job-btn", function() {
    ...
});

where this_modal is a reference to the current modal being created.

Upvotes: 2

Related Questions