tim peterson
tim peterson

Reputation: 24315

Unsetting event handling after Ajax while using jQuery on()

The JS code below works fine if loaded via a normal page load. However, if the page containing this code is refreshed via Ajax, then the click is registered multiple times, one for each time the page is refreshed via Ajax. You can tell this by either the number of times the word "Saved" is printed or by the number of times the console.log message "#SavedBtn clicked" appears.

Is there some way to unset the click handler when the page is loaded via Ajax?

HTML:

<button type='button' id='saveBtn'></button>

JS:

$(document.body).on('click', '#saveBtn', function(){
    var t='<span class="savedSpan">Saved</span>';
    $(this).after(t);
    console.log('#saveBtn clicked');
    $('.savedSpan').animate({
        color: "#FFF4D2"
        }, 1000).fadeOut();                           
});

Upvotes: 1

Views: 104

Answers (1)

jjnguy
jjnguy

Reputation: 138982

You could make a call to off() before calling on(). This will remove the handler before adding another one.

The code might look like:

$(document.body).off('click', '#saveBtn');
$(document.body).on('click', '#saveBtn', function(){
    var t='<span class="savedSpan">Saved</span>';
    $(this).after(t);
    console.log('#saveBtn clicked');
    $('.savedSpan').animate({
        color: "#FFF4D2"
        }, 1000).fadeOut();                           
});

Upvotes: 1

Related Questions