user967451
user967451

Reputation:

Is it possible to unbind specific event handlers in jQuery when 2 or more are the same?

Take a look at this code:

$(window).on('load resize scroll', function() {
    console.log('hello');
});

$(window).on('load resize scroll', function() {
    console.log('goodbye');
});

If at some point I want to prevent "hello" from being console logged but still want "goodbye" to be logged how to do that?

Because this:

$(window).unbind('load resize scroll');

Cancels both logs.

Upvotes: 1

Views: 246

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Name your handlers:

function sayHello() {
    console.log('hello');
}

function sayGoodbye() {
    console.log('goodbye');
}

$(window).on('load resize scroll', sayHello);
$(window).on('load resize scroll', sayGoodbye);

and when you want to stop saying hello just turn it off:

$(window).off('load resize scroll', sayHello);

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

use event namespaces

An event name can be qualified by event namespaces that simplify removing or triggering the event. For example, "click.myPlugin.simple" defines both the myPlugin and simple namespaces for this particular click event. A click event handler attached via that string could be removed with .off("click.myPlugin") or .off("click.simple") without disturbing other click handlers attached to the elements. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match. Namespaces beginning with an underscore are reserved for jQuery's use.

$(window).on('load.one resize.one scroll.one', function() {
    console.log('hello');
});

$(window).on('load.two resize.two scroll.two', function() {
    console.log('goodbye');
});

then

$(window).off('load.one resize.one scroll.one');

Upvotes: 4

Related Questions