Cancel jQuery event handling

ⅰ亾dé卋堺 提交于 2019-12-04 19:29:08


I have setup onclick event handler in the following manner:

element.onclick = function() { /*code */ }

Imagine there are event handlers setup using jQuery method bind() or similar handlers.

$('element').bind('click', function(){/*another function*/})

How can I prevent invoking handler defined with jQuery from the handler I have described in the beginning?

NB stopPropagation() and etc. jQuery's methods doesn't work from that function, because it is passed with native event object.


I'm not 100% sure what you're asking but maybe this will help:

You can create a new event object (compliant with W3C DOM) via jQuery's exposed Event constructor:

For example:

element.onclick = function(e) {
    var aBetterEventObject = jQuery.Event(e);
    // Now you can do what you want: (Cross-browser)

EDIT: Reading through your question again, I don't think propagation is the problem - you seem to want to cancel an event handler from running within an event handler - I'm not sure this is possible. You could just unbind all handlers (jQuery(elem).unbind('click')) but I don't think that's what you're after...


Following on from JimmyP's answer. I've tried this

$('#x').click( function(e){
document.getElementById('x').onclick = function(){

The jQuery event runs once in this example. I don't think you can rely on the order of handlers being invoked however you define them, so I guess you'll have to accept that the jQuery event might fire once. Adding the onclick first does prevent the jQuery event from firing at all but, as I said, I don't think that's reliable.


try to add the following line in the jQuery event handler:

return false;


Jquery has a method for namespacing events.

You can add, trigger and remove separate functions bound to the same event via namespaces:

$("a").bind("click.custom1",function(){ ... });
$("a").bind("click.custom2",function(){ ... });

As long as you unbind the namespaced event your normal onclick should be unaffected. You may have to bind two separate namespaces to the click event as above if that doesn't work.