SalmanShariati SalmanShariati - 2 months ago 10
jQuery Question

jQuery 3.x .off() after .on()

I simply used .off() method after .on() method for .click() method.

I'm really confused why click() event fires!



$('span').on('click', function () { $('p').text("You Clicked!") });

$('span').off('click', function () {
$('p').text("Ha Ha Ha!") });

span{
background-color:#ac0;
padding:5px;
cursor:pointer;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<span>Click Me!</span>
<p>*****</p>




Answer Source

You've misunderstood what the function is for at the end of the off() method. It isn't a callback, it's an event handler.

That function is supposed to be the same event handler function as the one you set initially. This is done this way so that you can remove an individual click handler.

function handlerA(e) {
  console.log('heard by A');
}

function handlerB(e) {
  console.log('heard by B');
}

// add both handlers to click events
$('span').on('click', handlerA);
$('span').on('click', handlerB);

// remove the first click event only, leaving the second
$('span').off('click', handlerA);

The above would only log heard by B when clicked.

To remove all click handlers, you need to omit the function entirely.

$('span').off('click');