user3445644
user3445644

Reputation: 91

Jquery to trigger animation and then div HTML change on hover glitches randomly

So I have a div that when you hover over it it's supposed to trigger an animation that moves another div a bit, increases its height, and then changes the HTML content inside that div, on hover out this process is reverted. The code works fine most of the time, but sometimes it reverts back in size and location but the content within it doesn't change back so it looks glitched; this seems to be kind of random. Here's my code:

    $("#event-1").hover(
        function() {
            $("#eo1").animate({
                "top": 0
            });
            $("#eo1").animate({
                "height": 240
            });
            setTimeout(function() {
                $("#eo1").html('NEW HTML HERE');
            }, 700);
        },
        function() {
            $("#eo1").animate({
                "height": 80
            });
            $("#eo1").animate({
                "top": 160
            });
            $("#eo1").html('ORIGINAL HTML HERE');
        }
    );

Is it because of the timeout to change the HTML which I set so that it would wait until the box had fully expanded before adding the new HTML?

I'll describe exactly what's happening when it glitches: the div moves up, it expands, the HTML changes to NEW, [hovers out], the HTML changes to OLD, the HTML changes to NEW, the div shrinks, the div moves down.

Upvotes: 0

Views: 214

Answers (2)

Bojan Petkovski
Bojan Petkovski

Reputation: 6933

Why do you complicate your script, make it simply like this http://jsfiddle.net/nyma1g7e/

$("#event-1").hover(
    function () {
        $("#eo1").stop().animate({
            "top": 0,
            "height": 240
        }, 700, function(){
            $("#eo1").html('NEW HTML HERE');
        });        
    },
    function () {
        $("#eo1").stop().animate({
            "height": 80,
            "top": 160
        }, 700, function(){
             $("#eo1").html('ORIGINAL HTML HERE');
        });
});

Upvotes: 2

Pointy
Pointy

Reputation: 413707

Just make sure you kill the timeout in the hover-out code, and also stop any animation:

    var timer = null;
    $("#event-1").hover(
        function() {
            $("#eo1").animate({
                "top": 0
            });
            $("#eo1").animate({
                "height": 240
            });
            timer = setTimeout(function() {
                $("#eo1").html('NEW HTML HERE');
            }, 700);
        },
        function() {
            clearTimeout(timer);
            $("#eo1").stop().animate({
                "height": 80
            });
            $("#eo1").stop().animate({
                "top": 160
            });
            $("#eo1").html('ORIGINAL HTML HERE');
        }
    );

That way a quick mouse movement will start the "in" operation, but then the "out" code will stop it.

Upvotes: 0

Related Questions