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);
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);
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With