How to update CSS3 animations when changing a class

So I have these CSS3 script

#place.us .level1 { background-position: -100px; background-color: #333; }
#place.gb .level1 { background-position: -100px; background-color: #CCC; }

@-webkit-keyframes place-pop-livel1 { 
    0% { bottom: -100px; } 
    100% { bottom: 30px; }
}
#place .level1 { 
    animation: place-pop-livel1 2s ease-out;
    -moz-animation: place-pop-livel1 2s ease-out; 
    -webkit-animation: place-pop-livel1 2s ease-out; 
}

When the page loads first, the div has #place.us, and the animation works fine. Now I want to change the div class to "gb" to make it #place.gbusing jquery, and as soon as the class changes, I want the same animation to happen.

My jquery code is simple

$('.change-city').live('click', function(){
    var city = $(this).data('city'); //gb or us
    $('#place').removeClass().addClass(city);
});

The class and property are changed .level1as specified in the CSS, but the animation is not executed. How can I make sure the animation is happening?

+5
source share
1 answer

I would recommend using CSS transitions, since they have a better browser overview, they are easier to manage, and they recover better (if the browser does not support transitions, it does the same without animation).

:

// after load add the animation
$(".level1").addClass("pop");

// after the animation is done hide it again
$(".level1").bind("webkitTransitionEnd mozTransitionEnd oTransitionEnd msTransitionEnd transitionend", function(){
  $(this).removeClass("pop");
});

$('.change-city').live('click', function(){
    var city = $(this).data('city'); //gb or us
    $('#place').removeClass().addClass(city).find(".level1").addClass("pop");
});

CSS

#place.us .level1 {background-color: #333; }
#place.gb .level1 {background-color: #CCC; }


#place .level1 {
  position: absolute;
  background-color: #000;
  width: 100px;
  height: 100px;
  bottom: -100px;
  -webkit-transition: bottom 2s ease;
  -moz-transition: bottom 2s ease;
  -o-transition: bottom 2s ease;
  -ms-transition: bottom 2s ease;
  transition: bottom 2s ease;
}


#place .pop {
  bottom: 30px
}

jsfiddle: http://jsfiddle.net/EmsXF/

+4

All Articles