Is there a way to temporarily override all element binding bindings using jQuery?

event.preventDefault() will override the default event behavior for the element. How to temporarily override all binding bindings, not just standard ones? Or is there a way to keep all click bindings so I can untie them and use them later?

Well, this is not the right answer, but a workaround. We can push the required handler over the stack and then use return false to stop other bindings. https://github.com/private-face/jquery.bind-first

+7
source share
3 answers

You can use jQuery.clone(true) what this does is return data for the element. A parameter that is set to true also allows you to copy all events.

So, if you clone an element into a variable, you can return the old click events by simply replacing your target element with its old clone (which has old events)

So it looks like this:

step 1: clone the target element using jQuery.clone(true) into a variable

step 2: remove all click events from the target using jQuery.off('click')

Step 3: bind your event to the target using jQuery.on('click' function etc...)

step 4: when you are done, replace the target element with your clone (which has old events)

Here is a JSFiddle for viewing pleasure

(Sorry for the simplicity of JSFiddle, I quickly made fun of it, and I have no example where I will use this.)

EDIT: I forgot to explain jQuery.clone(true)

+2
source

You can catch a click before it can bubble using

 element.addEventListener(type, listener[, useCapture]); 

This way you can catch a click before starting the jQuery click handler, like this (which I took from this stack question) :

 document.addEventListener('click', function(e) { e.stopPropagation(); }, true); 

For more information (and some IE <9 support) see developer.mozilla

Edit: Details about useCapture from Mozilla:

If true, useCapture indicates that the user wants to initiate a capture. After the capture starts, all events of the specified type will be sent to the registered listener before sending to any EventTarget under it in the DOM tree. Events that bubble up through the tree will not call the listener assigned to use the capture. For detailed explanations, see DOM Level 3 Events. If not specified, useCapture defaults to false.

+1
source

If you have control over all the JS code and you can link your own handler first, and all the other event handlers are jQuery related, you can do this:

 var overrideClick = false; $("#yourElementId").click(function(e) { if (overrideClick) { e.stopImmediatePropagation(); // e.preventDefault(); uncomment this if you want to prevent default action too } }); 

If any other part of your code has set overrideClick = true when necessary.

Demo: http://jsfiddle.net/NCa5X/

jQuery calls the handlers in the order in which they are bound, so you can use event.stopImmediatePropagation() to prevent other handlers from being called.

0
source

All Articles