UserX
UserX

Reputation: 1229

Animate and add class at the same time

I'm trying to add a class with top and left properties for animation, but the div just shifts to the added class attribute without animating.

#myClass.move {
    top:100px;
    left:100px; 
}     

The goal is to have the animation happen right when the class is added and animate based on the properties of the added class.

var shiftTop = parseInt($(".move").css("top")); 
var shiftLeft = parseInt($(".move").css("left")); 

$("#myClass").addClass("move").animate({top: "-="+shiftTop, left: "-="+shiftLeft}, 1000, function() {});

Is this possible?

Upvotes: 0

Views: 576

Answers (4)

freejosh
freejosh

Reputation: 11383

I'm assuming that you have an element with class .move in your document already, from which to read the shiftTop and shiftLeft values.

If all you need to do is change the top and left attributes you can remove the addClass step entirely, since the animate function adds them inline. If you do need the class applied after, do it in the animate callback.

Depending on your compatibility requirements you could also do this entirely with CSS, using transitions.

Upvotes: 0

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

Yes it's possible:

Add class before animate:
$("#myClass").addClass("move").animate({top: "-="+shiftTop, left: "-="+shiftLeft}, 1000);
demo

Add class after animate:

$("#myClass").animate({top: "-="+shiftTop, left: "-="+shiftLeft}, 1000, function() {
    $(this).addClass('move');
});


demo

Upvotes: 1

kei
kei

Reputation: 20491

Use jQueryUI.

Demo here

$("#myClass").click(function() {
    $(this).addClass("move", 1000);
});​

Upvotes: 3

Chad
Chad

Reputation: 5418

$('#myClass').animate({top: "-="+shiftTop, left: "-="+shiftLeft}, 1000, function() {
    $(this).addClass('#myClass');
});

Upvotes: 2

Related Questions