jQuery animation within hover() only fires on second time
Asked Answered
O

1

6

I'm using jQuery to animate a height change on hover().

Upon hover, it'll apply a .hover class, and upon clicking, it'll toggle a .expanded class. It mostly works, with proper animation, but only after the first time. The first time hover will skip the animation entirely.

I'm stumped - here's the offending code:

$('#expandingbox').hover(

    /*on mouseenter, if not expanded, add hover class*/
    function() {
    if (!$(this).hasClass("expanded")) {
        $(this).stop(true, true).addClass("hover", "slow");
    }},

    /*on mouseout, if not expanded, remove hover class*/
    function() {
    if (!$(this).hasClass("expanded")) {
        $(this).stop(true, true).removeClass("hover", "slow");
    }
}).click(function() {
    $(this).toggleClass("expanded", "slow");
});

I found somewhere that adding $('#expandingbox').trigger('mouseout') will fix this problem, but it didn't work for me. And here's an example reproducing the problem: http://jsfiddle.net/Qc42v/


UPDATE: Submitted a ticket, and it turns out it's a jQuery bug. The same code works with jQuery 1.5 (and the latest version of jQuery UI).

Odoric answered 11/6, 2011 at 1:20 Comment(2)
Have you considered using the animate?Kyl
@Kyl I guess I should just go with what works - I'll use animate() for now and file a bug, as @pixelfreak suggested.Odoric
D
2

This might be a legit jQuery UI bug. Adding some random class beforehand seems to fix it for me. Check: http://jsfiddle.net/Qc42v/9/

So basically like this:

/*on mouseenter, if not expanded, add hover class*/
function() {
if (!$(this).hasClass("expanded")) {
    $(this).addClass("xxx");
    $(this).stop(true, true).addClass("hover", "slow");
}},

If this looks too yucky for you, maybe just use the basic animate() function? Someone should definitely file a bug though :{

Dualism answered 11/6, 2011 at 1:41 Comment(1)
I can't believe that works! How did you think of doing that? I think I will file a bug, and try the animate(). I've never used that, so it was about time I learned it, I guess! Thanks!Odoric

© 2022 - 2024 — McMap. All rights reserved.