Mayank Pandeyz Mayank Pandeyz - 4 years ago 162
Ajax Question

Event listener works multiple times for ajax driven html

utilities.js:

// on is used because html is dynamic
$(document).on('click', '#next_campaign', function() {
console.log('hello');
});


layout:

<script src="utilities.js"></script>


view:

There is a view that is loaded using
ajax()
on layout that contains
#next_campaign
button in it.

The issue is, if the view is loaded n times then its listeners also works n time. Means if view is loaded 2 times then the click on
#next_campaign
wil trigger the event two times so the output will be hello 2 times like :


hello

hello


Can some one please guide me where I am doing wrong?

Answer Source

That because in every load the click event will be attached, you could use jQuery method off() to dettach the click event (if there's one) before attach it using on() :

$(document).off('click', '#next_campaign').on('click', '#next_campaign', function() {
    console.log('hello');
});

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download