CUDA
CUDA

Reputation: 165

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";
}

Upvotes: 13

Views: 25094

Answers (7)

Chinmoy Samanta
Chinmoy Samanta

Reputation: 1426

CustomAnimation is a small libary for animating html elements which is written in pure js.You can use this libary.

Upvotes: 0

Pablo Darde
Pablo Darde

Reputation: 6402

Simplest way via css.

https://jsfiddle.net/pablodarde/5hc6x3r4/

translate3d uses hardware acceleration running on GPU. http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-css

HTML

<div class="movingBox"></div>

CSS

.movingBox {
  width: 100px;
  height: 40px;
  background: #999;
  transform: translate3d(0,0,0);
  transition: all 0.5s;
}

.moving {
  transform: translate3d(200px,0,0);
  background: #f00;
}

JavaScript

const box = document.getElementsByClassName('movingBox')[0];

setTimeout(() => {
    box.className += ' moving';
}, 1000);

Upvotes: 0

Jefferson Steelflex
Jefferson Steelflex

Reputation: 17

I did a ton of research, and I finally learned how to do it really well.

I like to place my program in a window.onload function, that way it dosn't run the code until the page has finished loading.

To do the animation, make a function(I'll call it the draw function) and call it what ever you want except reserved words, then at the very end of the draw function call the requestAnimationFrame function and give it the name of the function to be called next frame.

Before the requestAnimationFrame function can be used it must be declared.

See the code below:

window.onload = function() {
  function draw() { //  declare animation function
    context.fillStyle = "white";
    context.fillRect(0, 0, 400, 400);
    requestAnimationFrame(draw); // make another frame
  }
  var requestAnimationFrame = // declare the 
    window.requestAnimationFrame || // requestAnimationFrame
    window.mozRequestAnimationFrame || // function
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame;
  draw(); // call draw function
}

Note: Nothing after the line that calls the draw function will run, so you need to put everything you want to run before the line that calls the draw function.

Upvotes: 2

Calvein
Calvein

Reputation: 2121

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.

Upvotes: 10

Blaster
Blaster

Reputation: 9110

With JavaScript, you will have to use setInterval function or this is how it can be done in jQuery:

$('#challengeOneImageJavascript').animate({left: '=-5'});

Adust value (5) as per your needs as well as direction via =- or =+

With Vanilla JavaScript:

var interval;
var animate = function(id, direction, value, end, speed){
    var div = document.getElementById(id);
    interval = setInterval(function() {
       if (+(div.style) === end) {
          clearInterval(interval);
          return false;
       }
       div.style[direction] += value; // or -= as per your needs
    }, speed);
}

And you can use it like:

animate('challengeOneImageJavascript', 'left', 5, 500, 200);

To stop animation any time, you would do:

clearInterval(interval);

Note: This just a very quick way to do it to give you an idea.

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58521

You would have to use a javascript timeout function, and change the css value a little at a time. The easiest way would be to increment by a set amount each time until a threshold is reached, which would give you a linear animation, which would look clunky and amateurish compared to jQuery's default swing animation which follows a bezier curve approximately like an s-curve.

Untested code should do the linear animation

var lefty = 0;
var animate = function(){
    lefty += 20;
    var div = document.getElementById('challengeOneImageJavascript');
    div.style.left = lefty +"px";
    if(lefty < 200)
      setTimeout(animate(),100);
}

animate()

n.b. there are lots of improvements to make to that block of code, but it should get you going...

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

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

Upvotes: 46

Related Questions