Reputation: 26288
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?
Upvotes: 0
Views: 76
Reputation: 67525
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.
Upvotes: 2