Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to temporarily override all click bindings on an element using jQuery?

event.preventDefault() will override default event behavior of an element. How can I temporarily override all click bindings and not just default ones? Or is there a way to save all the click bindings so I can unbind them and use them later?

Well this is not a proper answer but a workaround. We can push the required handler on top of the stack and then used return false to stop other bindings. https://github.com/private-face/jquery.bind-first

like image 389
Lokesh Suthar Avatar asked Jun 14 '13 10:06

Lokesh Suthar


2 Answers

You can use jQuery.clone(true) what this does is return data for an element. The parameter that is set to true means to also copy over all the events as well.

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

So it goes as follows:

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

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

step 3: bind your event to the target element with jQuery.on('click' function etc...)

step 4: when you're done replace the target element with its clone (which has the old events)

Here is a JSFiddle for your viewing pleasure

(Sorry for the simpleness of the JSFiddle I mocked it up quickly and I have no example situation where I would use this.)

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

like image 122
Michael Avatar answered Oct 07 '22 02:10

Michael


You may catch the click before it can bubble by using

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

This way you can 'catch' the click before triggering the jQuery click handler, like this (which I took from this stackoverflow 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 wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. If not specified, useCapture defaults to false.

like image 26
Severin Avatar answered Oct 07 '22 01:10

Severin