Reputation: 4096
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);
Upvotes: 3
Views: 3149
Reputation: 5094
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);
}
});
Upvotes: 5
Reputation: 91369
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.
Upvotes: 3