paint-brush
Animations in Browserby@teterin.pavel
8,724 reads
8,724 reads

Animations in Browser

by Pavel TeterinMay 29th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Animations can make any website visually appealing and user interactive, and in this article, we’ll cover the two primary ways of creating them – two CSS techniques and two JavaScript-based methods, explain the basics, use cases, and provide clear usage examples, guiding you from simple to more complex concepts.
featured image - Animations in Browser
Pavel Teterin HackerNoon profile picture

Animations can make any website visually appealing and user interactive, and in this article, we’ll cover the two primary ways of creating them – two CSS techniques and two JavaScript-based methods, explain the basics, use cases, and provide clear usage examples, guiding you from simple to more complex concepts.


We’ll start with the CSS techniques.

CSS Transitions

CSS transitions are the simplest and the most straightforward way to animate your components. They are a means to control animation speed when changing CSS properties: the change is not instantaneous; it rather takes place over a period of time. Say, while usually a change of the element colour from black to white is immediate, with CSS transitions enabled, the colour will change at the time interval and with the easing that you have set. So, the main idea behind CSS transitions is to ensure smooth and swift changes between different states of a website element.


Here are some common use cases for CSS transitions: state changes in properties like colour, opacity, position, or size, navigation menus, loading and progress bars, hover effects, image galleries, form validation, page transitions, and others.


Transitions, however, have their limitations and are most often used when the animation is not too complex. Below are some examples when transitions are not the best choice and you should opt for other methods that we’ll cover later in the article:


  • If changes to the element size, appearance or position are frequent,
  • If you need more control over timing and easing or for synchronisation with other events.


Here is an example of how a transition is defined:

.animated {
  transition: transform 2s linear;
}


In this example, if the element changes transform property it will be animated for 2 seconds with linear timing function.

CSS Animations

Now that we’ve discussed CSS transitions, let’s proceed with CSS animations, which are used for more complex animations. With CSS animations, you can set how the animated element should behave at a given time during the animation sequence, and control the duration, number of repetitions, start of the animation, and its other characteristics.


When compared to CSS transitions, the latter, for example, have only the initial and the final states, while CSS animations can have as many intermediate keyframes as you need, giving you more control and flexibility. Another difference is that transitions always require a trigger to run, and animations work automatically when the page loads. Also, CSS animations can be looped, run forwards and backwards or alternate between the states.


Common use cases often intersect: both transitions and animations are used for loading indicators, page transitions, hover effects, with animations offering a wider range of possibilities. Transitions, at the same time, are easier to work with and you’ll find yourself using them more often than not: reach out for animations when transitions are not sufficient for your purposes. For example, when you need to grab a user’s attention by adding a pulsating or bouncing button or want to smoothly fade, slide, or scale in and out a web element.


As for CSS animations limitations, be careful using numerous or complex animations when dealing with older devices or multiple browsers, when performance might become an issue. The same goes for mobile user experience: excessive animations may, for instance, increase page load time, frustrating your users. Also, take into account design considerations and don’t overuse animations if the website should look minimalistic.

Example

.animated {
  width: 100px;
  height: 100px;
  background-color: black;
  animation-name: animated;
  animation-duration: 10s;
}

@keyframes animated {
  0%   {transform: rotate(90deg);}
  25%  {transform: rotate(180deg);}
  50%  {transform: rotate(270deg);}
  100% {transform: rotate(360deg);}
}

Here animated element performs four rotations in 10 seconds.


With both CSS transitions and animations covered, it’s time to showcase the JavaScript-based approach to animations.

Web Animation API

Web Animation API is a relatively new addition to the browser that allows you to animate elements with JavaScript as easily as with CSS transitions/animations but with the added value of JS, like full control of an element’s styles at every step, which means that you can slow down your animations, pause, stop or reverse them, and manipulate elements any way you need, making it easy to customise them beyond the capabilities of CSS-based animations. For example, you can use a timing function for an animation in CSS but, with Web Animation API, you can specify a timing function for each keyframe as well as for the entire animation.


So, Web Animation API is useful where you need to scrub through a timeline. Another good example are more interactive animations, like charts that continuously update based on new information. In this case, a lot of dynamic processing is happening, changing the heights of the bars and how they should change, and that’s something that you will probably want to assign values directly to the different values on the page with JavaScript as new information appears, rather than to deal with CSS states.

Example

const animation = document.getElementById("alice").animate(
  [
    { transform: "rotate(120deg)", backgroundColor: "red"},
    { transform: "rotate(240deg)", backgroundColor: "green"},
    { transform: "rotate(360deg)", backgroundColor: "blue"},
  ],
  {
    duration: 3000,
    iterations: Infinity,
  }
);
// Here you can control animation
animation.play();
// animation.cancel();
// animation.finish();

requestAnimationFrame()

requestAnimationFrame() is a native browser method that requests that the browser call a specific function to update an animation before the next repaint. It makes it possible to create a smooth animation loop that takes advantage of the browser’s optimal rendering timing, allowing it to optimise when to animate.


When compared to Web Animation API, the latter is a higher-level API that offers full control of your animations, which includes defining keyframes, managing playback, and integrating with CSS animations, while requestAnimationFrame() focuses on scheduling animation frames but it can be used in combination with CSS animations and Web Animation API.

// Generic animation function
function animate((fun, duration) {
  const start = Date.now();
  function animationCb() {
    const progress = Math.min((Date.now() - start)/ duration, 1);
    fun(progress);
    if(progress === 1) {
      return;
    }
    requestAnimationFrame(animationCb);
  }
  requestAnimationFrame(animationCb);
}

// Using our own animation function
const target = document.getElementById('target')
animate(progress => {
 target.style.transform = `rotate(${Math.round(360*progress)}deg)`

}, 5000);


In conclusion, both declarative and imperative approaches work well if chosen correctly for specific purposes. When deciding on the best method for your particular case, remember to take into account such factors as the complexity of the desired animation, your project’s processing power, browser compatibility, your overall website design considerations, and others.