Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activating Webkit CSS3 animation using Javascript

I am looking to use Webkit CSS3 to move a absolutely positioned DIV from one location to another on the screen when a button is pressed, by changing its left and right CSS properties. However, all the examples for doing this that I saw use a static CSS rule to apply this transition.

I don't know the new position before hand, so how do I apply this CSS3 transition dynamically?

like image 616
jeffreyveon Avatar asked Jun 13 '10 19:06

jeffreyveon


People also ask

How do you trigger an animation in CSS?

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS. We add the @keyframes property with the animation we want to animate. It'll animate from the from styles to the to styles.

Does CSS animation use JavaScript?

CSS transitions and animations are ideal for bringing a navigation menu in from the side, or showing a tooltip. You may end up using JavaScript to control the states, but the animations themselves will be in your CSS. Use JavaScript when you need significant control over your animations.

Does css3 animation need JavaScript?

CSS animations make it possible to do simple animations without JavaScript at all. JavaScript can be used to control CSS animations and make them even better, with little code.

What is WebKit in CSS animation?

WebKit now supports explicit animations in CSS. As a counterpart to transitions, animations provide a way to declare repeating animated effects, with keyframes, completely in CSS. With a recent nightly build, you can see the above animation in action.


1 Answers

Once you've defined the transition it will apply no matter how you change the CSS values on the element. So you can just apply an inline style with JavaScript and the element will animate. So with CSS like this:

left: 100px;
top: 100px;
-webkit-transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;
-moz-transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;
-o-transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;
transition: top 300ms ease-in 100ms, left 200ms ease-in 50ms;

Have a function like this:

function clickme() {
    var el = document.getElementById('mydiv');
    var left =  300;
    var top =  200;
    el.setAttribute("style","left: " + left + "px; top: " + top + "px;");
}

And you will see the animation when you call the function. You can get the values for left and top from where ever you like. I've done a full example.

like image 160
robertc Avatar answered Oct 26 '22 20:10

robertc