Reputation:
How can I, with simple JavaScript, without switching classes and ids, without jQuery and jQuery plugins, remake a CSS3 animation, but only with JavaScript? In CSS3 it's so simple by using @keyframes
, but how to do it with JavaScript? What will the code be?
How can I create an animation?
var start = document.getElementById("start");
start.style.animation = ... // I don't know what to do
start.style.animationname = ... //Or something like this?
I'm still new to JavaScript.
UPD
I will try to simply describe, what I need: I need a div, when I click on it, it has to move +5px to the left. But I read, that the DOM animation isn't so good, so I asked about using CSS3-like animation in JavaScript.
Upvotes: 2
Views: 4299
Reputation: 5682
Why not just do this:
var start = document.getElementById("start");
start.style.left = + 10 + 'px';
CSS:
#start{
-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
-o-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
This would move your element 10px to the right in .5 of a second.
Edit regarding your edit:
To do that you could do this:
function move_left(current_pos){
var element = document.getElementById("start");
var start_left = element.style.left;
var end_pos = parseInt(start_left, 10) + 5;
if(current_pos != end_pos){
element.style.left = element.style.left + 1 + 'px';
current_pos = parseInt(element.style.left, 10);
return move_left(current_pos);
}else{
return 'finished';
}
}
Upvotes: 5
Reputation: 36236
To animate you'll need to define a starting state, and a target (or finished) state and an easing function to control the rate of change.
Rather than start from scratch I'd suggest leveraging an existing solution, there is a LOT of code out there to help you do this.
Check out: https://github.com/sole/tween.js
Upvotes: 2