Mark Wilson Mark Wilson - 1 year ago 112
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.


Here is my approach:

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

So, whenever mouseleave event occurs, I am unbinding
and then with a
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 Source

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.


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


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

function onHover(){

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=""></script>
<a href="#">Foo</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download