sambath sambath - 3 years ago 152
Ajax Question

js stop click function subsequent execution after call back in ajax of itself

On the first click myClick() has been called again in itself of myLoad() then at the second click, this myClick() will execute two times

=> The following causes two subsequent execution of
click event of #myBtn by one click


How to avoid or stop this? Please anybody suggest me new logical method or which way to stop this.



$(function(){
myLoad()
})
function myClick(){
$("#myBtn").click(function(){
myLoad();//load new every click
});
}
function myLoad(){
$("#myCnt").load('ajax.php', {"data":"some"}, function(){
myClick()//to live the click event works after ajax load
})
}




Answer Source

Problem with your implementation is that in each call to myClick() an new event handler is attached to button.

You can use .off() to remove existing event handler attached using .on().

function myClick(){
  $("#myBtn").off('click').on('click', function(){
    myLoad();//load new every click
  });
}

A better approach would be to use .on() method with Event Delegation approach, when generating elements dynamically.

General Syntax

$(document).on('event','selector',callback_function)

In place of document you should use closest static container.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

A good read Direct and delegated events

Modify you code as

$(function() {
  myLoad();

  $(document).click("click", "#myBtn", function() {
    myLoad(); //load new every click
  });

})

function myLoad() {
  $("#myCnt").load('ajax.php', { "data": "some"}, function() {
    //No need to call my click
  })
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download