Juicy
Juicy

Reputation: 12520

Animate back to original style

If I have this:

.circle {
   height: 20px;
   width: 20px;
   border-radius: 10px;
}

I can animate scaling it bigger like this:

$('.circle').animate({
    'height' : 40px,
    'width' : 40px,
    'border-radius': 20px
});

But what is the best way to then downscale it back to it's original css (using an animation, so just stripping the inline html style won't work)?

I can think of two ways:

The downside of the second method is a lot of variables and lines of code needed if there are several fields.

I'm not expert at jQuery and I think there must be an easier way I'm missing.

Upvotes: 1

Views: 194

Answers (3)

Alessandro Incarnati
Alessandro Incarnati

Reputation: 7246

I suggest you to use CSS for setting the presentation layer and toggleClass in jQuery to add and remove CSS properties by toggling a class.

In this case using jQuery toggleClass() instead of addClass() and removeClass() avoids the use of an if else statement to check if the class .animated is already present to the .circle class.

JS / jQuery

$('.circle').click(function(){
     $(this).toggleClass('animated');
});

CSS

.circle {
   height: 200px;
   width: 200px;
   border-radius: 100px;
   transition: all .5s ease;
   background-color:red;
}

.circle.animated {
   height: 400px;
   width: 400px;
   border-radius: 200px;
   background-color:blue;
   transition: all .5s ease;

}

I edited the dimensions of the circle to make it more visible and change the background color too. If you click it you will see the transitions applied by CSS. This way you will keep your code clean, and it will be much easier to edit by editing the CSS properties of each class.

DEMO http://jsfiddle.net/eNUpJ/12/


Good rule of thumb:

HTML for structure
CSS for presentation
JS (or jQuery as JS framework) for behaviour

Upvotes: 6

guest271314
guest271314

Reputation: 1

Try

$(function () {
    $(".circle").animate({
        "height": "40px",
         "width": "40px",
         "border-radius": "20px"
    }, {
        duration: 2500,
        done: function (promise) {
            var back = {};
            $.each(promise.props, function (key, value) {
                back[key] = String(Number(value.replace("px", "") / 2) + "px");
            });
            return $(this).animate(back, promise.duration);
        }
    });
});

jsfiddle http://jsfiddle.net/guest271314/5vY2s/

See http://api.jquery.com/animate/#animate-properties-options

Upvotes: 0

EternalHour
EternalHour

Reputation: 8621

Put your transition directly afterward.

$('.circle').animate({
    'height' : 40px,
    'width' : 40px,
    'border-radius': 20px
},'fast', function(event) {
$('.circle').animate({
    'height' : 20px,
    'width' : 20px,
    'border-radius': 10px
}'slow');

Upvotes: 3

Related Questions