user3427494
user3427494

Reputation: 43

How can I toggle animate a div?

I tried installing Jquery UI so that I could easily add animation to the toggleClass funciton, but it only animates when adding the class, and not when removing the class (or moving back left to it's original position).

jQuery('#menu').click(function() {
  jQuery('#wrap').toggleClass('move-right', 1000);
  });

CSS

#wrap {
   position: relative;
   bottom: 22px;
   max-width: 1150px;
   margin: 0 auto;
   padding: 20px;
}

.move-right {
   left: 9%;
}

So How can I get this to animate both ways?

It's just a simple slide to the right, then back left. I thought jQuery UI would be easiest, but if I don't need it even better

Upvotes: 0

Views: 108

Answers (3)

Sarah
Sarah

Reputation: 754

You can use CSS3 transition to define a transition property (left) and time (1s), see: http://jsfiddle.net/m3sEn/1/ This doesn't require jQuery UI.

CSS:

#wrap {
    left: 0;
    transition: left 1s;
}

#wrap.move-right {
    left: 9%;
}

Upvotes: 0

Max Langerak
Max Langerak

Reputation: 1207

You could try it by using a boolean and if the boolean is true try moving it the other way. Then your code should be something like this:

JS:

var right = false;
jQuery('#menu').click(function() {
  if(!right) {
    jQuery('#wrap').toggleClass('move-right', 1000);
    right = true;
  } else if(right) {
    jQuery('#wrap').toggleClass('move-left', 1000);
    right = false;
  }
});

CSS:

#wrap {
   position: relative;
   bottom: 22px;
   max-width: 1150px;
   margin: 0 auto;
   padding: 20px;
}

.move-right {
   left: 9%;
}

.move-left {
   right: 9%;
}

This basically checks whether 'wrap' has moved right on clicking the button. If not, it moves it to the right, otherwise, it moves to the left.

Upvotes: 0

wirey00
wirey00

Reputation: 33661

add a left position to #wrap

then change your .move-right selector to be more specific

#wrap {
   position: relative;
   bottom: 22px;
   max-width: 1150px;
   margin: 0 auto;
   padding: 20px;
   left:0;
}

#wrap.move-right {
   left: 9%;
}

http://jsfiddle.net/TrcLy/

Upvotes: 1

Related Questions