Jonathan Lam
Jonathan Lam

Reputation: 17351

jQuery animate() and CSS transition happening separately on same event

I was playing around with CSS transition along with jQuery animate() in this JSFiddle.

However, when I combined the two, the CSS happens first, and then the jQuery animations happens afterwards, occassionally with a pause.

Both of the animations are bound to the hover event of the <div> (CSS: :hover, jQuery: .hover()), but they do not happen simultaneously.


In case you need it, here is all the code:

/* DON'T MIND THIS FIRST SECTION ... JUST FOR CENTERING */
var div = $("div#fiddle");
var win = $(window);

var reset = function() {
    var wWidth = win.width();
    var wHeight = win.height();
    
    var dWidth = div.width();
    var dHeight = div.height();
    
    div.css({
        marginTop: wHeight / 2 - dHeight / 2,
        marginLeft: wWidth / 2 - dWidth / 2
    });
}

reset();

win.resize(reset);

/* THIS SECTION IS THE PROBLEMATIC ONE */
div.hover(
	function() {
    	$(this).animate({
        	marginTop: "-=50",
            marginLeft: "-=50"
        }, 2000);
    },
    function() {
    	$(this).animate({
            marginTop: "+=50",
            marginLeft: "+=50"
        }, 2000);
    }
);
html, body {
    background-color: #444444;
    padding: 0;
    margin: 0;
}

div#fiddle {
    width: 200px;
    height: 200px;
    box-sizing: border-box;
    background-color: #8888dd;
    border-radius: 100px;
    
    -webkit-transition: all 2s;
    -o-transition: all 2s;
    -moz-transition: all 2s;
    -ms-transition: all 2s;
    transition: all 2s;
}

div#fiddle:hover {
    height: 300px;
    width: 300px;
    border-radius: 150px;
}
<!-- The HTML if you want it  -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fiddle"></div>

(It's a bit hard to see in the snippet, but it can give you an idea, especially if you set it to full page. But it's best on JSFiddle.net)


Any idea why this is happening, and any solutions? Also, any thoughts on why there is sometimes a pause between the two events, and sometimes not? Thanks.

Upvotes: 1

Views: 437

Answers (1)

Darren Gourley
Darren Gourley

Reputation: 1808

Ok, so in all honesty I was tinkering. Remove the duration time (2000) from the animations in your jquery. Looks like the transition on the css handles the duration.

div.hover(
    function() {
        $(this).animate({
            marginTop: "-=50",
            marginLeft: "-=50"
        });
    },
    function() {
        $(this).animate({
            marginTop: "+=50",
            marginLeft: "+=50"
        });
    }
);

http://jsfiddle.net/sp2ufh4o/1/

Upvotes: 1

Related Questions