JavaScript Animations!Why Not.?

Avijit Nanda
Beginner's Guide to Mobile Web Development
7 min readMar 19, 2018

“How do I animate stuffs in my website?”, John asked.

“Its simple , you can use CSS3 Animations & Transitions in you’re web pages”, Riley replied.

But Mike said , “Why use CSS3 when you can use JavaScript.” “With JavaScript you can have better control over the animations.”

JavaScript Animations has the following advantages over CSS3 Animations:-

i) Flow Control:-

Imagine you have a square box which is continuously rotating on one section of the web page , but your client demands that the user should have the liberty to pause, stop or reverse its rotations. Well, it would be really difficult to do it using CSS3 . But using JavaScript it would seem just easy as a pie!

ii) Animate Multiple Properties:-

Now lets say you want to scale your div element and simultaneously start rotating it and changing color of the border. Using CSS3 you cannot animate individual properties distinctly.But, JavaScript allows you to animate literally any numeric property in variety of ways.

iii) Well-Structured Code:-

JavaScript codes are well structured. JavaScript animations are generally written in form of functions which increases the modularity as well as the comprehensibility of the source code.

iv) Compatibility:-

CSS3 transitions doesn’t work in older browsers. What’s more — every browser engine handles them differently. So why not use something different which has better compatibility with the browsers i.e, JavaScript.

Enough of those boring chit-chats. Lets get some coding done.

Animation in JavaScript is basically done using three methods:

  1. setInterval( ),
  2. Element.animate( ),
  3. requestAnimationFrame( ).

setInterval( ) Method:

Using this method we will create animation by programming gradual changes in a element style.

But first let us make a simple web-page to demonstrate the animations.Here’s the code ,

To make animations possible the animated element must be animated relative to a parent container. It can be seen from the code that the div element with idmyContaineracts as the parent with relative positioning and the div element with id myAnimation acts as the element to be animated with absolute positioning.

To make gradual changes in the element we use a timer. And when the timer interval is small , the animation looks continuous. As per the animation the button when clicked calls the function myMove().

We initialize the elem variable which stores the animated div id , so that we do not have to refer the div element again and again using all those big commands. There is pos variable which will be used to update the position of the element(initially zero). And then we are start the setInterval() function and pass in the frame function and that will be run every 10millisecond. In the frame() function when the element reaches the bottom right i.e,pos == 350 , we are going to stop running the frame()function after every 10 milliseconds using the function clearInterval() . And in else condition the statements are to make the element animate by making the element move diagonally by one pos and we can easily use different other style elements to animate it.

Element.animate( ) method:

Element.animate method is part of the web animations API and this method is actually the animation method with the best performance . It has some compatibility issues with older version of web browsers. The updated code with element.animate() .

The div element used in element.animate has absolute positioning . This element has been given the id item and that item will be used as item.animate .

While calling the item.animate() we pass two things . The first thing that is passed is an object formatted to represented a set of key-frames. “What is a key-frame?”, you ask.Well key-frames are states that define the starting and ending points of any smooth transition. And the second thing that is passed are the options .

In the first argument you can change pretty much any CSS property . Now as per the code, in the first key-frame it’s going to set the transform , as in the first state where scale is 100% , background is red, opacity is 100% and offset is 0 . In the second key-frame we’re going to do a transform , have the scale to go to 50% , background to blue, opacity to 50% and offset to 0.2 and rotate it by 270 degrees . And in the third key-frame we’re going to do a transform , have the scale go back to 100% , background back to red, opacity to 100% and offset to 1 and rotate it back to 0 degrees. There can other CSS properties which can be also changed using this method.

The second argument that is passed are options.Option is either an integer representing the animation’s duration (in milliseconds), or an object containing one or more timing properties.Some of the options are:

id — A property unique to animate(). A DOMString with which to reference the animation.

delay — The number of milliseconds to delay the start of the animation. Defaults to 0.

direction — Whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). Defaults to "normal".

duration — The number of milliseconds each iteration of the animation takes to complete. Defaults to 0. Although this is technically optional, keep in mind that your animation will not run if this value is 0.

easing — The rate of the animation's change over time. Accepts the per-defined values "linear", "ease", "ease-in", "ease-out", and "ease-in-out", or a custom "cubic-bezier" value like "cubic-bezier(0.42, 0, 0.58, 1)". Defaults to "linear".

endDelay — The number of milliseconds to delay after the end of an animation. This is primarily used when sequencing animations based on the end time of another animation. Defaults to 0.

fill — Dictates whether the animation's effects should be reflected by the element(s) prior to playing ("backwards"), retained after the animation has completed playing ("forwards"), or both. Defaults to "none".

iterationStart— Describes at what point in the iteration the animation should start. For example, 0.5 would indicate starting halfway through the first iteration and with this value set, an animation with 2 iterations would end halfway through a third iteration. Defaults to 0.0.

iterations — The number of times the animation should repeat. Defaults to 1, and can also take a value of Infinity to make it repeat for as long as the element exists.

Some other options include:

composite— Determines how values are combined between this animation and other, separate animations that do not specify their own specific composite operation. Defaults to replace.

add — Dictates an additive effect, where each successive iteration builds on the last. For instance with transform, a translateX(-200px) would not override an earlier rotate(20deg) value but result in translateX(-200px) rotate(20deg).

replace — Overwrites the previous value with the new one.

spacing— Determines how key-frames without temporal offsets should be distributed during the animation's duration. Defaults to distribute.

The Last Method ;)

requestAnimationFrame( ) Method:

The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.

This method is similar to setInterval() but it is more optimized for animation in the browser. The benefits include:

  1. The browser can optimize the process , so that the animations will be smoother.
  2. Animations in inactive tabs will stop, allowing the CPU to cool down.
  3. More battery friendly.

In this example it can be seen that the button for toggle animation is going to call the toggleAnimation(). What this function does is that it either chooses to start the animation or stop the animation. So if that toggle is off then we’re going to set it true and then we’re going to run the animation i.e, window.requestAnimationFrame()and then we’re going to call the step() function. And that’s how the step function initially starts. However if it’s already running i.e, else condition, we’re going to set the toggle to false and we’re going to cancel animation frame. So if you call the method cancelAnimationFrame() and then pass a stopId it will just stop the animation.

Here’s the code:

This stopId stores the value returned by the method window.requestAnimationFrame(). Now in the step() function we are the going to use the other variables which were initialized at the beginning of the script. So progress variable is how we’re going to determine what pixel we want the animated element to be at on the screen .We will take the timestamp that was passed by value to function and subtract start from it. Now the timestamp will always keep increasing and the difference will always vary accordingly. The difference in milliseconds obtained would then be divided by 10 which will be equal to the number of pixels we want and we’re going to add 50 just because we don’t want the element to start at the very top of the page.

Then we’re just going to set element.style.top = progress+'px' because the number of pixels to be displaced by the animation element is stored in progress variable. And then at the end , the step() will be called again using the window.requestAnimationFrame() and passing step to it.

This last statement is just going to keep calling the step() function over and over again and every time it gets called, a new timestamp values is passed to it. And that’s what is going to increase the value in progress which will increase the top style and will slowly make the animation element go down.

“Oh, just using these three methods we can create animations using JavaScript!!”,John exclaimed.

“Well, pretty much that is it .Its time you get your hand dirty and create some beautiful animations using JavaScript.” Mike replied.

I hope my article will be informative and helpful for some. And if it does prove to do so , please do not hesitate to hit that clap button.

THANK YOU.

--

--