Saqib Shahzad
Saqib Shahzad

Reputation: 1002

same script loading multiple times on click event javascript/jquery

$(document).click(function() {
  $('.settings').click(function(){
    alert();
  });

});

I am loading this script on click event as I cannot load this on ready event. Now when I click on button with class settings first time, nothing happens as expected as the script is loaded after I click on button.

Second time, I click on this button, alert is shown one time (as expected).

But the unexpected behavior is, when I click for third time, alert is shown 2 times. When I click for 4th time, alert is shown 3 times and so on.

One possible reason that I can think of is, script was loading every time when I click.

What could be the issue? How can I prevent same piece of script from loading again and again?

Thanks!

Upvotes: 1

Views: 1244

Answers (3)

Chinmoy Samanta
Chinmoy Samanta

Reputation: 1426

This issue will be solved if Click event related to document is fired for only one time when you click first time in settings button.

If you want an event handler to only fire once then take a look at .one(): http://api.jquery.com/one

 $(document).one("click",function() {
      $('.settings').click(function(){
        alert();
      });
    });

Upvotes: 2

CptArcanium
CptArcanium

Reputation: 66

As @Bravo already suggested you need the off handler. You add a click event handler everytime you click. So you should remove the previous click handler before adding another. Something like:

$(document).off('click').on('click', (function() {
  $('.settings').off('click').on('click', function(){
    alert();
  });
});

Upvotes: 0

joshweir
joshweir

Reputation: 5617

Each time you click, you add a new handler for .settings. Try this:

$(document).on('click', '.settings', function() {
  alert();
});

Upvotes: 4

Related Questions