Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple of the same event handler using .off()

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?

like image 219
StudioTime Avatar asked Aug 25 '16 11:08

StudioTime


People also ask

How do I get rid of event handler?

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.

Which function is used to remove an existing event handler?

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.

Can we use the same handler multiple times on the same task?

Handler should be executed only once.

Can you have multiple event handlers?

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.


1 Answers

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>
like image 100
BenG Avatar answered Sep 23 '22 04:09

BenG