jQuery Hover Listener Unbinding

jQuery has a great helper function called hover which takes two functions as it’s values.

$('#hover_div').hover(function()
{
/* something to do on mouseenter */
},
function()
{
/* something to do on mouseleave */
});

Great when you want a simple way of doing something when your mouse enters or leaves the selected element(s).

But then I needed to unbind the listener from the elements and I couldn’t for the life of me work out how.

/* WRONG */
$('#hover_div').unbind('hover');
 
/* WRONG */
$('#hover_div').unbind('mouseover').unbind('mouseout');
 
/* update 2: WRONG - but hopefully in the next release */
$('#hover_div').unbind('mouseenter mouseleave');
 
/* CORRECT */
$('#hover_div').unbind('mouseenter').unbind('mouseleave');

So there you go. That’s how to unbind hover().

3 comments.

  1. /* CORRECT */
    $(‘#hover_div’).unbind(‘mouseenter’).unbind(‘mouseleave’);

    /* update: CORRECT AND SHORTER */
    $(‘#hover_div’).unbind(‘mouseenter mouseleave’);
    /* in FF/Mac this did not seem to work while the above did… */

  2. John,

    You are correct. The simple example below reveals that the mousenter is unbound but the mouseleave event remains.
    Looking at the jquery code, when binding events, the type (’mouseenter mouseleave’) string is split at space characters, while unbinding does not.

    $(function()
    {
    	$('#div').hover( function(){ $(this).css('border','solid 1px #000') },function(){ $(this).css('border','solid 1px #ccc') } );
    	setTimeout(function(){ $('#div').unbind('mouseenter mouseleave') },5000)
    });
  3. I tried all the examples listed above and no success. =(