user1974333
user1974333

Reputation: 31

jQuery addClass() removeClass() methods

I am having a problem with jQuery methods .addClass() .removeClass

JsFiddle : http://jsfiddle.net/HEM7Q/4/

$(document).ready(function () {
  $(".button").click(function(e) {
  $(".position1").animate({left:"400px"},2000, function(e){
     $(".position1").addClass("position2").removeClass("position1");
     })
  });
});

see, initially the css.left is 20 px (because its defined in the class .position1). now, I animate the div till its left become 400px. After the animation is completed, I addClass position2 (where left is 50px) and I removeClass position1.

so shouldn't the div come back to left == 50 px after the completion of the animation? why is it not happening, and what is the right code for it?

Upvotes: 1

Views: 162

Answers (3)

Engineer
Engineer

Reputation: 48803

You need to remove inline left from the styles,as inline styles take precedence over CSS classes:

$(".position1").animate({left:"400px"},2000, function(e){
    $(".position1").css("left","");  //Removing 'left' which was added by animation

    $(".position1").addClass("position2").removeClass("position1");
})

DEMO

Upvotes: 0

dlock
dlock

Reputation: 9577

Because inline styling has higher priority than external styles. You may want to change your left property in .position2 to left: 10px !imporant to enforce using the property value.

http://jsfiddle.net/HEM7Q/6/

Upvotes: 0

Grant Thomas
Grant Thomas

Reputation: 45058

I'll say that the animate method is amending inline styles to get the desired effect which remain present even when the animation is completed (unless you actively revert) and this takes precedence over your defined style classes.

Upvotes: 2

Related Questions