Method off
The off
method allows you to unbind an event handler from an element. To bind a handler, you can use the off
method.
Syntax
This is how we remove an event handler from an element, the first parameter is one or more events separated by spaces as a string, the second is an additional filtering selector of descendants inside the element (it should match what we passed to the on
method when we attached the handler). To remove all delegated events, pass the value '**'
. The second parameter is optional. The third is the handler function (which we attached), to which the event object is passed, or we pass false
:
$(selector).off(events, [selector], handler function(event object));
You can use the off
method in a different way, then the first parameter is passed a JavaScript object, where the keys are the event type, and the values are the handler functions that we added to the element:
$(selector).off({'event type': handler}, [selector]);
We can simply pass one parameter as a jQuery.Event
object:
$(selector).off(event);
If we don't pass parameters to the method, we will unbind all attached handlers from the element:
$(selector).off();
Example
Let's add a handler function testFunc
to the paragraphs. But let's immediately remove the handler from the second paragraph, so that clicking on the second paragraph will not lead to anything (if we comment out the last line of code, we will see how the event is triggered by clicking on the second paragraph):
<p id="test1">click1</p>
<p id="test2">click2</p>
function testFunc(event) {
alert(event.data.text);
}
$('#test1').on('click', {text: 'aaa'}, testFunc); // add handler
$('#test2').on('click', {text: 'bbb'}, testFunc); // add handler
$('#test2').off('click', testFunc); // delete handler