Mark Wilson Mark Wilson - 1 month ago 23
Javascript Question

jQuery unbind and bind

The case is: when I hover over a link some task should happen and when I leave the area/ mouseleave happens the hovering for the link should stay disabled for 1 second and work again.

DEMO PLNKR:

http://plnkr.co/edit/m6SnDzuo2MA5hoYUEoPc?p=preview

Here is my approach:

$("a").hover(function (event) {
event.preventDefault();
alert('hovered');
}, function () {
$("a").unbind('mouseenter mouseleave');
setTimeout(function () {
$("a").bind('mouseenter mouseleave');
}, 1000);
});


So, whenever mouseleave event occurs, I am unbinding
mouseenter
and
mouseleave
and then with a
setTimeout
and binding them again.

So, now it is unbinding fine but after a second the events are not rebinding.

Please help if I am doing anything wrong here.

Answer

First you bind to hover, and when the cursor leaves you will unbind mouseenter and mouseleave. But you are not assigning any function to it. Do you actually want to re-assign to the previous hover-event?

In the example you have given you do not set a handler.

From the docs.

eventType

Type: String A string containing one or more DOM event types, such as "click" or "submit," or custom event names.

handler

Type: Function( Event eventObject ) A function to execute each time the event is triggered.

function onHover(){
  alert('hovered');
}

function onHoverLeft(){
  console.log('onHoverLeft called');
  $("a").off('mouseenter mouseleave');
    setTimeout(function () {
      console.log('setTimeout is done. Will rebind hover now.');
      $("a").hover(onHover, onHoverLeft);
    }, 2000);  
}
$("a").hover(onHover, onHoverLeft);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Foo</a>