简体   繁体   中英

How can I make sure my events always fire in jQuery? [Hover callback not firing]

I have a BG image animation that relies on the hover callback to revert to it's original state. If I move the mouse quickly over the links, the hovered state sticks. My guess is that I'm moving the mouse off before the first animation completes, so the callback doesn't register.

Is there a more bulletproof way to write this function?

$('.nav li a').hover(function() {
    $(this).addClass('hovered', 300);
}, function() {
    $(this).removeClass('hovered', 300);
});

(it uses a BGimg plugin to support the speed parameter on add/removeClass)

Testable here: McPherson Industries

This is a common problem and cannot be fixed, I'm afraid – it's up to the browser to keep up with events, and if it can't, well, you're out of luck.

It might be jQuery's fault also, though. Hard to say without dwelling into the source code. Anyways, there's a easy workaround:

$('.nav li a').hover(function() {
    // When element is hovered, remove hovered state from all elements..
    $('.hovered').removeClass('hovered');
    // ..and add it to this one.
    $(this).addClass('hovered', 300);
}, function() {
    // This is only needed when exiting an element and not enterin another one
    $(this).removeClass('hovered', 300);
});

This might not be 100% certain, but it's better than your current.

What is the 300 value in the addClass method ? it does not take two parameters.. just one
Api reference: http://api.jquery.com/addClass/ ( ok,noticed the plugin )

It works just fine for me .. all links revert back to their original image, no-matter how fast i move the mouse..

Update

Ok i see the problem now..

  • Chrome is OK ( the only one it seems.. )
  • Firefox shows the problem..
  • IE shows the problem

Update 2 It seems to me that the problem is with the plugin you use.. It ignores queued requests to the same object until the current animation has finished.. So if you hover out before the first one has completed it will not return to normal..

I can't help more on this, sorry ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM