trackpopular
trackpopular

Reputation: 61

How to avoid multiple loading of jQuery functions?

I am using following code on my page which I am loading in ajax.

$(document).ready(function() {
    $('#button_id').click(function() {
      //Do Something          
    });
});

Now When I click on the button action happens multiple times. I know that its happening because I am loading the ajax page multiple times.

Please help me solve this.

Upvotes: 2

Views: 1795

Answers (4)

Hafsul Maru
Hafsul Maru

Reputation: 393

A cleaner solution would be to remove that code from the ajax loaded HTML and use one single event handler in the master page

Upvotes: 0

Joe Fitzgibbons
Joe Fitzgibbons

Reputation: 331

If I am wrong about your implementation I apologize. Your problem may exist because the binding is created on first page load and then on subsequent ajax loads with new scripts being inserted and creating duplicate bindings. You should prevent any bindings from being generated on ajax loads to prevent duplicate bindings unless you are good with cleanup.

If the button you are clicking on exists in the ajax loaded area then you should use delegation to ensure that the click handlers still work.

For example:

$( "body" ).on( "click", "#button_id", function() {
    //do something
});

This will add a binding to the body element, but more specifically to the id #button_id. A click event on the button will propagate and bubble up to the body element (or whatever parent element you choose).

This makes it so that dynamic elements can be inserted in the DOM and only one event handler is needed to listen for it.

No need for .on() or .off() calls for individual ajax loads. This allows your bindings to be much cleaner.

Of course, if your button is not likely to exist on the page all the time then it would not be a good idea to keep extra bindings. Only create these types of binding if they are always needed to prevent optimization issues.

Upvotes: 2

DD.
DD.

Reputation: 1075

I guess your problem is the event is firing many times.

To fire only once try this:

$(document).ready(function() {
    $('#button_id').on("click",function(e) {
      e.preventDefault(); // This prevents the default non-js action (very used for anchors without links or hashes)
      e.stopPropagation(); // Prevent the bubling of the event and spread more times

      //Do Something          
    });
});

If doesn't work with e.stopPropagation(); try with e.stopInmediatePropagation();

Adding documentation for the last method I suggested. It could solve your problem. http://api.jquery.com/event.stopimmediatepropagation/

Upvotes: -1

Wex
Wex

Reputation: 15695

You can use .off() to remove existing listeners:

$(function() {
    $('#button_id').off('click').click(function() {
      //Do Something          
    });
});

Upvotes: 5

Related Questions