tags:

views:

69

answers:

3

when i leave the selector, the unhover will not occur if i move too fast:

  $("#item").hover(function(){

  $(this).addClass("hover");

  }function(){

  $(this).removeClass("hover");

  });
A: 

You can use .live to set up the eventhandlers before you create the item.

or

function thover() {
  $(this).toggleClass("hover");
}

$("#item").mouseEnter(thover).mouseLeave(thover);

or

$("item").hover(function () { $(this).toggleClass("hover",true); },
                function () { $(this).toggleClass("hover",false); }
);
Hogan
how is this using `live`? and how is it different to the code in the OP?
nickf
@nick: I did not give an example of live (there is a "or" there). Both answers are different, one uses mouseEnter and mouseLeave and the other uses toggleClass.
Hogan
+1  A: 

I was unable to reproduce it. Wrote this in Firebug in this very page:

$("p").hover(function() { $(this).html('a') }, function() { $(this).html('b') });

Always works even if I move really fast. Maybe it's because you forgot a comma before the second function, in your code? What browser do you use?

Andreas Bonini
A: 

Here's a solution:

CSS:

#item:hover, #item.hover {
    background-color: #f0f;
}

Javascript:

if ($.browser.msie) { // I'm not sure if IE7 or 8 support :hover yet
    $('#item').hover(
        function() { $(this).addClass('hover'); },
        function() { $(this).removeClass('hover'); }
    );
}

This code makes your edge case thinner.

Decent browsers which have good CSS support shouldn't be slowed down with Javascript calls just because IE is faulty. If someone insists on using IE, then they'll still get hover effects, but sometimes it might stick. Do you really care about these people that much?

nickf