Joe.wang
Joe.wang

Reputation: 11793

Disable all the events of DOM

I am trying to find an easy way to disable all the jQuery event handler of DOM element, like hover, click, etc. I know I can use the unbind to do that. But it will need a of code to do that. I just want to know is there any switch of jQuery to control this? Also, I know there is a solution using global variable to make it. I don't think it is good to write hard code like this.

//in some event handler
if (sometag)
{
   //do something.

}

It is not elegant for the code. Any idea or something I don't know?

Upvotes: 0

Views: 2305

Answers (3)

LeGEC
LeGEC

Reputation: 51780

Your question is pretty wide and general. If you could state your precise use case, someone could probably give you a better answer.

Another pattern to activate / deactivate event handlers on a dom node is to delegate event handling to a parent node, and use classes to toggle the handlers on and off.

What is event delegation ? You will find a simple answer here.

Here is an example :

//HTML code :

<ul id="myList">
    <li>
        <input class="cbActivate" type="checkbox" /> <a href="#" class="link">first item</a>
    </li>
    <li>
        <input class="cbActivate" type="checkbox" /> <a href="#" class="link">second item</a>
    </li>
    <li>
        <input class="cbActivate" type="checkbox" /> <a href="#" class="link">third item</a>
    </li>
</ul>

//javascript
$('.cbActivate').on('click', function () {
    $(this).closest('li').find('a.link').toggleClass('active');
});
// handling clicks on 'a.active' links is delegated to the parent '#myList' node
$('#myList').on('click', 'a.active', function () {
    alert("I'm an activated item !");
});

Here is the corresponding jsfiddle

Upvotes: 1

m90
m90

Reputation: 11812

In case you really want to unbind ALL event handlers you can just use .off() without any arguments:

$('p').off();

As an altenative to that you could use namespaced events, which would allow you to unbind all handlers of a namespace:

$('p').on('click.ns', handler).on('mouseover.ns', handler2).on('mouseout.otherns', handler3);
$('p').off('.ns'); //only the first two handlers are unbound

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074008

If you're talking about just your own handlers, and you want to have a global "on/off" switch for them, then having a central variable your handlers test is a perfectly reasonable approach, not bad or inelegant. (I wouldn't actually make it a global variable, just a variable that all of the handlers have access to.)

Alternately, you can namespace your events:

$("some selector").bind("click.myevents", handler);
$("some selector").bind("hover.myevents", handler);
// ...

...and use the namespace to unbind all of them:

$("*").unbind(".myevents");

...but there's no easy way to turn them back on again, and the overhead for that seems a bit high.

Upvotes: 2

Related Questions