views:

3555

answers:

6

How do I unbind "hover" in jQuery?

This does not work:

$(this).unbind('hover');
+1  A: 

All hover is doing behind the scenes is binding to the mouseover and mouseout property. I would bind and unbind your functions from those events individually.

For example, say you have the following html:

<a href="#" class="myLink">Link</a>

then your jQuery would be:

$(document).ready(function() {

  function mouseOver()
  {
    $(this).css('color', 'red');
  }
  function mouseOut()
  {
    $(this).css('color', 'blue');
  }

  // either of these might work
  $('.myLink').hover(mouseOver, mouseOut); 
  $('.myLink').mouseover(mouseOver).mouseout(mouseOut); 
  // otherwise use this
  $('.myLink').bind('mouseover', mouseOver).bind('mouseout', mouseOut);


  // then to unbind
  $('.myLink').click(function(e) {
    e.preventDefault();
    $('.myLink').unbind('mouseover', mouseOver).unbind('mouseout', mouseOut);
  });

});
bendewey
Correction, After looking at the jquery src hover is actually binding to mouseenter/mouseleave. You should do the same.
bendewey
+24  A: 

$(this).unbind('mouseenter').unbind('mouseleave')

or more succinctly (thanks @Chad Grant):

$(this).unbind('mouseenter mouseleave')

Crescent Fresh
or $(this).unbind('mouseenter mouseleave')
Chad Grant
+7  A: 

Unbind the mouseenter and mouseleave events individually or unbind all events on the element(s).

$(this).unbind('mouseenter').unbind('mouseleave');

or

$(this).unbind();  // assuming you have no other handlers you want to keep
tvanfosson
+12  A: 

Actually, the jQuery documentation has a more simple approach than the chained examples shown above (although they'll work just fine):

$("#myElement").unbind('mouseenter mouseleave');
Phil.Wheeler
A: 

unbind() doesn't work with hardcoded inline events.

So, for example, if you want to unbind the mouseover event from <div id="some_div" onmouseover="do_something();">, I found that $('#some_div').attr('onmouseover','') is a quick and dirty way to achieve it.

Jaytop
A: 

I found this works as second argument (function) to .hover()

$('#yourId').hover(
 function(){
  // Your code goes here
 },
 function(){
  $(this).unbind()
 }
});

The first function (argument to .hover()) is mouseover and will execute your code. The second argument is mouseout which will unbind the hover event from #yourId. Your code will be executed only once.

Afwas