I assign two event handlers:
$('#myElement').on('click', '.classA', doSomething);
$('#myElement').on('click', '.classB', doSomethingElse);
I want to remove both the handlers. I know I can do:
$('#myElement')
.off('click', '.classA')
.off('click', '.classB');
I thought it would be possible in one line, but both of these fail:
$('#myElement').off('click', '.classA, .classB');
$('#myElement').off('click', '.classA .classB');
Is there a way to do it in one command?
Using the removeEventListener() method The JavaScript built-in function removeEventListener() removes an event handler from an element for a connected event. For instance, you can use removeEventListener() to get rid of a click event listener if a button is disabled after one click.
The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.
Handler should be executed only once.
Only one event handler can be assigned for every event in an element. If needed the handler can be replaced by assigning another function to the same property. Below we show how to set a simple greet() function for the click event using the onclick property.
After looking at the source, you will see in the off
:-
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
}
Which means the selector needs to be exactly how it was created.
Therefore you need to use:-
$('#myElement').on('click', '.classA', function() { alert('A'); });
$('#myElement').on('click', '.classB', function() { alert('B'); });
$('#myElement').off('click', '.classA').off('click', '.classB');
$('#myElement').on('click', '.classA', function() { alert('A'); });
$('#myElement').on('click', '.classB', function() { alert('B'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myElement">
<button class="classA">A</button>
<button class="classB">B</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With