Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript animation

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";
}
like image 221
CUDA Avatar asked Jun 26 '12 18:06

CUDA


People also ask

Can you animate with JavaScript?

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.

Which js is used for animation?

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.

Is CSS animation better than js?

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.

Do I need JavaScript for animation?

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.


2 Answers

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).

like image 75
Niet the Dark Absol Avatar answered Sep 20 '22 11:09

Niet the Dark Absol


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.

like image 20
Calvein Avatar answered Sep 18 '22 11:09

Calvein