Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop a CSS Animation

So I've got this nice CSS animation here and I would like it to loop.

I have almost no experience with CSS animations yet sadly and no Idea how to do this. I'd really appreciate if somebody here could help me out a bit. Thank you!

HTML

<div id="msg">Weeeeeee</div>

Javascript

$("#msg").click(function() {
    var duration = 1400;
    $msg = $(this);
    $msg.css("-webkit-transform", "scale(2)")
        .css("-webkit-transition-timing-function", "ease-out")
        .css("-webkit-transition-duration", duration + "ms");
    setTimeout(function () {
        $msg.css("-webkit-transform", "scale(1)")
            .css("-webkit-transition-timing-function", "ease-in")
            .css("-webkit-transition-duration", duration + "ms");
    }, duration);
});

CSS

#msg { font-size: 40pt; font-weight:bold; text-align:center; line-height: 120pt; }
like image 954
Matthias Avatar asked Jan 13 '13 19:01

Matthias


1 Answers

Praveen's solution should be closer to what you asked for, but I'll provide a solution using CSS3 animations instead of using jQuery to animate transitions. IMO it is easier to maintain and understand:

CSS

@-webkit-keyframes foo {
  from {
    -webkit-transform:scale(1);
  }
  to {
    -webkit-transform:scale(2);
  }
}

Then JS:

$("#msg").click(function() {
    var duration = 1400;
    $msg = $(this);
    //syntax is: animation-name animation-duration[ animation-timing-function][ animation-delay][ animation-iteration-count][ animation-direction]
    $msg.css("animation", "foo " + duration + "ms ease infinite alternate");
});

Fiddle

I didn't use the optional animation-delay parameter in the above, the rest should be pretty straightforward. infinite iteration count with alternate direction will execute the animation indefinitely alternating the animation direction from (from to to ) to (to to from) until you call $msg.css("animation", "") to remove the animation.

ps. jQuery 1.8+ will do the prefixing in the JS automatically for you.
Of course, you still have to prefix the CSS to work in non-webkit browsers though. Prefixr should do it.

Fiddle with prefixed CSS.

like image 172
Fabrício Matté Avatar answered Sep 30 '22 17:09

Fabrício Matté