19

What is the use or difference of combining .off with .click?

$('#link').off('click').on('click',function(){});

vs.

$('#link').on('click',function(){});

What are the advantages of combining them?

3 Answers 3

28

This adds a new click event handler:

$('#link').on('click', function(){});

This removes all existing click event handlers that were attached with .on() (if any) and then adds a new click event handler:

$('#link').off('click').on('click', function(){});
6
  • your answer was simple and understandable. But this .off behaviour can be achieved using event.preventdefault() right. ? Commented Jul 17, 2017 at 5:42
  • Well, not really. Where do you want to put event.preventdefault()? Commented Jul 17, 2017 at 5:45
  • If there is any other click event handler in my current click - I can prevent it by event.preventdefault() right.? what are the differents.? Commented Jul 17, 2017 at 5:47
  • 2
    No, it doesn't. It only prevents the default action of an element (e.g. a submit button submitting the form, or a link element loading the URL). It doesn't prevent any previously attached click events. Commented Jul 17, 2017 at 5:55
  • Especially helpful to include the off if the code is called often. Or else you could be attaching multiple .on('click') handlers.
    – farrellw
    Commented Dec 5, 2017 at 20:39
3

From the jquery documentation,

The .off() method removes event handlers that were attached with .on(). See the discussion of delegated and directly bound events on that page for more information. Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names. When multiple filtering arguments are given, all of the arguments provided must match for the event handler to be removed.

In your question,

$('#link').off('click').on('click',function(){});

It will simply remove any previous event handler attached to the event and create a new one.

2

We use $('#link').on('click',function(){}); when we know that there's no other click function is already bind to this element or even if another click function is a bind, then that's not hindering our click function. We use .off to unbind(stop) click functionality from all places for this element and then we use .on click to bind only our click functionality.

Not the answer you're looking for? Browse other questions tagged or ask your own question.