Skip to content Skip to sidebar Skip to footer

How To Reset An Event Handler After Calling .off() In Jquery

Why is my second body.on() not working? I added the .off() because if not both mousewheel events triggered with only one mousewheel down event... Isnt the second body.on() supposed

Solution 1:

Your code registers two mousewheel event handlers on the body object. When the mousewheel event occurs and the event handler callback functions are called, the first event handler then calls $("body").off(); which deregisters BOTH event handlers so you will get no future events.

At that point in time, you no longer have any event handlers on the body object.

If you want an event handler to only be called once, then you can use .one(). Other than that, it is not clear why you have two separate event handlers so therefore it's not clear what else to advise.

Generally, there's no reason to have two separate event handlers for the same event. Whatever work you want to do, you can just carry out that work in one single event handler. If you only want to carry out some of the work during some events, then just implement logic inside that single event handler to decide which work to carry out any time the event handler is called (using if statements and the like).

If you only want to deregister one of the event handlers, then you have to use a named function with the event handler $('body').on('mousewheel', funcName); so you can call $('body').off('mousewheel', funcName) to deregister just that particular event handler.


Using a named function works like this:

$(document).ready(function() {

  functionhandleWheel(event) {
    if (event.deltaY < 0) {
      if (!$(".both").hasClass('rotated')) {
        $(".both").css('transform', 'rotate(180deg)');
        setTimeout(function() { $(".both").addClass('rotated') }, 1000);
      } 
    }
    // disengage just this event handler and no others
    $("body").off('mousewheel', handleWheel);
  }

  $("body").on('mousewheel', handleWheel);

});

Post a Comment for "How To Reset An Event Handler After Calling .off() In Jquery"