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

jerome picture jerome · Jan 11, 2011 · Viewed 40.4k times · Source

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.

Answer

Mathias Bynens picture Mathias Bynens · Jan 11, 2011

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;
  });