Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override all JavaScript events bound to an element with a single new event

Assuming that there are a large number of elements throughout the site that have an unknown number and type of events bound to them.

If I need to override all of these events with one single bound event, and only that event will fire, what are some recommendations?

I would be binding the event to a click event handler, and I am using jQuery.

Thanks in advance.

like image 527
jerome Avatar asked Jan 11 '11 15:01

jerome


1 Answers

You’re looking for jQuery#unbind.

To remove all event handlers on an element or a set of elements, just do:

$('.some-selector').unbind(); 

To unbind only click handlers, use unbind('click'):

$('.some-selector').unbind('click'); 

To unbind all click handlers and immediately bind your own handler after that, you can do something like this:

$('.some-selector').unbind('click').click(function(event) {   // Your code goes here }); 

Note that this will only work for events bound using jQuery (using .bind or any jQuery method that uses .bind internally). If you want to remove all possible onclick events from a given set of elements, you could use:

$('.some-selector')   .unbind('click') // takes care of jQuery-bound click events   .attr('onclick', '') // clears `onclick` attributes in the HTML   .each(function() { // reset `onclick` event handlers     this.onclick = null;   }); 
like image 152
Mathias Bynens Avatar answered Sep 20 '22 03:09

Mathias Bynens