Learn Javascript

Animation

Creating movement using CSS and JS

slides | md

CSS Transitions

CSS transitions let you to change property values smoothly, over a given duration.

The below div will expand to 100% of its container over 2 seconds when you mouse over it (see code).

div {
  width: 10%;
  height: 100px;
  background-color: red;
  transition: width 2s;
}
div:hover {
  width: 100%;
}

CSS Animation

CSS animations let you apply several property values across multiple points ("keyframes") in time.

The below div will move to several positions on the screen, and then return to its origin per the keyframes in the code sample.

div {
  width: 30px;
  height: 30px;
  background-color: red;
  position: relative;
  animation-name: dontBeASquare;
  animation-duration: 4s;
}
@keyframes dontBeASquare {
  0%   { left:0px; top:0px; }
  25%  { left:200px; top:0px; }
  50%  { left:200px; top:200px; }
  75%  { left:0px; top:200px; }
  100% { left:0px; top:0px; }
}

CSS animation frameworks

There are several CSS frameworks dedicated to animation.

Using Javascript

Fundamentally, to animate is to change properties over time—something that Javascript can also do natively!

The circle moves to the right by n pixels until its position reaches the width of the window and resets using Javascript and requestAnimationFrame()

let ele = document.querySelector('div');
let leftPos = 0; // starting position
function move(timestamp){
  leftPos += 5;
  ele.style.left = leftPos + 'px';
  console.log(ele.style.left)
  if (leftPos > window.innerWidth)
    leftPos = -100;
  // continue animating
  requestAnimationFrame(move);
}
// start the animation
requestAnimationFrame(move);

Anime.js

Perhaps the most capable free JS framework available. My demos (Bouncing ball and Curtain transitions) are pale when compared to the examples in the docs and others you can find on codepen

See the Pen Anime.js v2.0 logo animation by Julian Garnier (@juliangarnier) on CodePen.

Scroll Animation

Listed (I believe) by complexity, ascending...

Presentation comments ...

EXAMPLE

EXAMPLE

EXAMPLE