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?
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(){});
.off
behaviour can be achieved using event.preventdefault()
right. ?
Commented
Jul 17, 2017 at 5:42
event.preventdefault()
?
Commented
Jul 17, 2017 at 5:45
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
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
.on('click')
handlers.
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.
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.