Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to found if an event already bound with jQuery [duplicate]

I was using a syntax like

$("body").on("click", ".className", function(){
    // some code
});

it was working fine, then I reloaded the entire page with ajax (no browser refresh), then the event started firing twice, another refresh - fired thrice and so on.

then I converted the code to

$("body").off("click", ".className").on("click", ".className", function(){
    // some code
});

it's fixed the issue to some extent. Even after this I am getting multiple firing in some scenarios. Is there a way to find out if there are existing 'on' events bound more than once on the element, remove them all and bind it for one time only?

Not sure if this is a valid question, or I was able to explain it clearly.

like image 408
Souvik Banerjee Avatar asked Nov 01 '22 03:11

Souvik Banerjee


1 Answers

If you are delegating everytime you are loading the page with ajax it will bind again and again on body's children .classname thus causing the unwanted effect

$(function () {
    $("body").on("click", ".className", function () {
        // some code
    });

    function loadpage() {
        //ajax call
    }
    loadpage();
});

Try to put your event delegation outside loadpage function

like image 66
Anton Avatar answered Nov 14 '22 08:11

Anton