-1

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>
SalmanShariati
  • 3,873
  • 4
  • 27
  • 46

2 Answers2

3

You're trying to remove a different handler function than was originally assigned.

Instead, create a reference to the function and add/remove it by that reference:

var clickHandler = function () { $('p').text("You Clicked!") };

$('span').on('click', clickHandler);
$('span').off('click', clickHandler);
David
  • 208,112
  • 36
  • 198
  • 279
2

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');
Soviut
  • 88,194
  • 49
  • 192
  • 260