I am trying to animate a div
moving 200px
horizontally in JavaScript.
The code below makes it jump the pixels, but is there a way to make it look animated without using jQuery?
function () {
var div = document.getElementById('challengeOneImageJavascript');
div.style.left = "200px";
}
JavaScript animations can use any timing function. We covered a lot of examples and transformations to make them even more versatile. Unlike CSS, we are not limited to Bezier curves here. The same is about draw : we can animate anything, not just CSS properties.
1. Anime.js is a lightweight JavaScript animation library with a simple, yet powerful API. It works with CSS properties, SVG, DOM attributes and JavaScript Objects. Anime. js is arguably one of the best animation libraries.
The fact is that, in most cases, the performance of CSS-based animations is almost the same as JavaScripted animations — in Firefox at least. Some JavaScript-based animation libraries, like GSAP and Velocity. JS, even claim that they are able to achieve better performance than native CSS transitions/animations.
You can use CSS and JavaScript to create animations. What you use depends on the complexity of the animation. For simple two-state animations, I recommend you use CSS transitions. For more complicated animations, I recommend you use CSS animations or JavaScript.
Here is a basic animation setup:
function animate(elem,style,unit,from,to,time) {
if( !elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+unit;
if( step == 1) clearInterval(timer);
},25);
elem.style[style] = from+unit;
}
To use:
animate(
document.getElementById('challengeOneImageJavascript'),
"left","px",0,200,1000
);
This example will animate the given element to slide linearly from 0px to 200px over a time of 1 second (1000 ms).
You can easily do this through CSS3-Transition :
#challengeOneImageJavascript {
-webkit-transition: left .2s;
-moz-transition: left .2s;
-o-transition: left .2s;
transition: left .2s;
}
Though, it is not supported by IE9 and earlier browser versions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With