$(document).on('click', '#slider_icons_wrapper.play', function(event) {
var slider_icons_wrapper = $('#slider_icons_wrapper');
slider_icons_wrapper.attr('class', 'pause');
autoSlider(cur_img_div_pos);
showButton('play_icon');
console.log('play');
});
$(document).on('click', '#slider_icons_wrapper.pause', function(event) {
var slider_icons_wrapper = $('#slider_icons_wrapper');
slider_icons_wrapper.attr('class', 'play');
clearInterval(inter);
showButton('pause_icon');
console.log('pause');
});
This code works fine for the first time the document is loaded.
When user navigates to another page, via ajax call (document does not refresh), and returns to the page that contains #slider_icons_wrapper div, the function executes twice when user clicks this div. If user navigates again and return, the function executes 3 times and so on!
What am I doing wrong?
Edit#1
When user navigates to another page, element #slider_icons_wrapper is removed from the DOM. When it is injected back via ajax call, the click event is firing on more time, each time. I have tried to unbind the click event when user leaves this page but the same thing happens
seems the event listener is being added to the document for every page return. try adding them on document.ready —
user1026361 also makes a good point to remove your listeners before adding them again. however, I believe that using .off( ) without a selector will remove all listeners added to that element via .on( ). if you take the .off( ).on( ) approach I would suggest using a namespace: