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

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


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


I would like to provide a thought without removing all events all together (just override them).

If your new one single bound event (we call it "click" here) is specific to the element it binds to, then I believe you can ignore any other events simply by stopPropagation() function. Like this

$("specific-selector").on("click", ".specific-class", function (e) {  e.stopPropagation()  // e.stopImmediatePropagation()  /* your code continues ... */});

It will stop events bubbles up, so your other events won't fire. use stopImmediatePropagation() to prevent other events attached onto the same elements as "click" does.

For example, if "mouseleave" event is also bind to $("specific-selector .specific-class") element, it won't fire, too.

At last, all other events won't fire on this element but your new "click" element.

The unsolved question is, what if other events also use stopPropagation()? ... Then I think the one with best specification wins, so try to avoid complex, too many events is final suggestion.

You can see "Direct and delegated events" on jQuery site for more information.


Looks like this is pretty simple actually:

$('#foo').unbind('click');$('#foo').bind('click', myNewFunction);

Thanks for your responses though.