Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if event handlers are already binded to an element?

Tags:

jquery

bind

I am using jQuery to bind event handlers to elements, but maybe there is also a way to check using normal JavaScript as well...

If I am using some code like shown below, is there a way to test if the elements already have event handlers added? When I run the function again (to update an img src), then events are binded a second time, and then the next time a third time, etc. What is the easiest way?

$(window["tdImg_"+i]).add(window["tdImgSize_"+i]).bind('click', toggleImageSize);
like image 835
theMaxx Avatar asked Jan 26 '26 12:01

theMaxx


2 Answers

Here is a solution:

$(window["tdImg_"+i]).each(function(){
    if(!this.boundToggleImageSize){
        $(this).bind('click', toggleImageSize);
        this.boundToggleImageSize = true;
    }
});

That way, you don't have to unbind all click events (if you have different bound functions on the same elements).

EDIT

As suggested by millimoose in the comments:

$(window["tdImg_"+i]).each(function(){
    if(!$(this).data("boundToggleImageSize")){
        $(this).bind('click', toggleImageSize);
        $(this).data("boundToggleImageSize",true);
    }
});
like image 173
mbinette Avatar answered Jan 28 '26 04:01

mbinette


The easiest approach would be to unbind the event and re-bind it again:

$(window["tdImg_"+i]).add(window["tdImgSize_"+i]).unbind('click').bind('click', toggleImageSize);

Otherwise, you'd have to access the events data, using $(el).data("events"), and manually detect if the event was already bound. Also note that this approach excludes inline event handlers.

like image 43
João Silva Avatar answered Jan 28 '26 02:01

João Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!