Advertisement
  1. Code
  2. JavaScript

JavaScript-Based Animations Using Anime.js, Part 1: Targets and Properties

Scroll to top
This post is part of a series called JavaScript-Based Animations Using Anime.js.
JavaScript-Based Animations Using Anime.js, Part 2: Parameters

Anime.js is a lightweight JavaScript-based animation library. You can use it to animate different CSS properties, SVG or DOM attributes on a webpage. The library allows you to control all aspects of the animation and provides a lot of ways for you to specify the elements that you want to target or the properties that you want to animate.

You have full control over the sequence in which the animations are played or how synchronized the animations of different elements are with respect to each other. The library supports all modern browsers.

In this tutorial series, you will learn about all the features of Anime.js so that you can use them in real-life projects with ease.

Before diving deep into the topic, let's install the library first. You can use either npm or Bower to perform the installation by running the following commands:

1
npm install animejs
2
3
bower install animejs

You can also download the library and include it in your project or directly link to the latest version of the library hosted on a CDN.

1
<script src="path/to/anime.min.js"></script>

After a successful installation, you are now ready to use this library to add interesting animation to your elements. We will start with the basics of the library, focusing on one particular area at a time.

Specifying Target Elements

To create any animations using Anime.js, you will have to call the anime() function and pass it an object with key-value pairs that specify the target elements and properties that you want to animate, among other things. You can use the targets key to tell Anime.js which elements you want to animate. This key can accept values in different formats.

CSS Selectors

You can pass one or more CSS selectors as a value for the targets key.

1
var blue = anime({
2
  targets: '.blue',
3
  translateY: 200
4
});
5
6
var redBlue = anime({
7
  targets: '.red, .blue',
8
  translateY: 200
9
});
10
11
var even = anime({
12
  targets: '.square:nth-child(even)',
13
  translateY: 200
14
});
15
16
var notRed = anime({
17
  targets: '.square:not(.red)',
18
  translateY: 200
19
});

In the first case, Anime.js will animate all the elements with a blue class. In the second case, Anime.js will animate all the elements with either the red or blue class. In the third case, Anime.js will animate all the even children with a square class. In the last case, Anime.js will animate all the elements with a square class that don't have a red class.

DOM Node or NodeList

You can also use a DOM node or a NodeList as a value for the targets key. Here are a few examples of setting the targets as a DOM node.

1
var special = anime({
2
  targets: document.getElementById('special'),
3
  translateY: 200
4
});
5
6
var blue = anime({
7
  targets: document.querySelector('.blue'),
8
  translateY: 200
9
});
10
11
var redBlue = anime({
12
  targets: document.querySelectorAll('.red, .blue'),
13
  translateY: 200
14
});
15
16
var even = anime({
17
  targets: document.querySelectorAll('.square:nth-child(even)'),
18
  translateY: 200
19
});
20
21
var notRed = anime({
22
  targets: document.querySelectorAll('.square:not(.red)'),
23
  translateY: 200
24
});

In the first case, I have used the getElementById() function to get our special element. The querySelector() function is used to get the first element that has the blue class. The querySelectorAll() function is used to get all the elements within the document that match the specified group of selectors.

There are a lot of other functions that you can use to select the target elements that you want to animate. For example, you can get all the elements with a given class name using the getElementsByClassName() function. Similarly, you can also get all the elements with a given tag name using the getElementsByTagName() function.

Any function that returns a DOM node or a NodeList can be used to set the value of the targets key in Anime.js.

Object

You can also use a JavaScript object as a value for the targets key. The key of that object is used as an identifier, and the value is used as a number that needs to be animated.

You can then show the animation inside another HTML element with the help of additional JavaScript. Here is the code to animate the values of two different keys of an object.

1
var filesScanned = { count: 0, infected: 0 };
2
3
var scanning = anime({
4
  targets: filesScanned,
5
  count: 1000,
6
  infected: 8,
7
  round: 1,
8
  update: function() {
9
    var scanCount = document.querySelector('.scan-count');
10
    scanCount.innerHTML = filesScanned.count;
11
    
12
    var infectedCount = document.querySelector('.infected-count');
13
    infectedCount.innerHTML = filesScanned.infected;
14
  }
15
});

The above code will animate the scanned files count from 0 to 1,000 and the infected files count from 0 to 8. Keep in mind that you can only animate numerical values this way. Trying to animate a key from 'AAA' to 'BOY' will result in an error.

We have also used a callback function for the update key that is called on every frame while the animation is running. We have used it here to update the count of scanned and infected files. However, you could go a step further and show users an error message when the number of infected files goes over a certain threshold.

Array

The ability to specify a JavaScript array as the target comes in handy when you have to animate a bunch of elements that fall under different categories. For example, if you want to animate a DOM node, an object, and a bunch of other elements based on CSS selectors, you can do so easily by putting all of them inside an array and then specifying that array as a value for the targets key. The following example should make it clearer:

1
var multipleAnimations = anime({
2
  targets: [document.querySelectorAll('.blue'), '.red, #special'],
3
  translateY: 250
4
});

Properties That Can Be Animated in Anime.js

Now that you know how to specify different elements that you want to animate, it is time to learn about all the properties and attributes that can be animated using the library.

CSS Properties

Anime.js lets you animate a lot of CSS properties, like the width, height, and color, for different target elements. The final values of different animatable properties like background-color and border-width are specified using a camel case version of that property. Therefore, background-color becomes backgroundColor, and border-width becomes borderWidth. The following code snippet shows how to animate the left position and the background color of a target element in Anime.js.

1
var animateLeft = anime({
2
  targets: '.square',
3
  left: '50%'
4
});
5
6
var animateBackground = anime({
7
  targets: '.square',
8
  backgroundColor: '#f96'
9
});

The properties can accept all kinds of values that they would have accepted when used in regular CSS. For example, the property left could be set to 50vh, 500px, or 25em. You could also specify the value as a bare number. In this case, the number would be converted to a pixel value. Similarly, the background color could be specified as a hexadecimal, RGB, or HSL color value.

CSS Transforms

You can also animate different CSS transform properties using Anime.js. Translation along the x and y axes can be achieved using the translateX and translateY properties. Similarly, it is possible to scale, skew or rotate an element along a specific axis by using the scale, skew and rotate property corresponding to that specific axis.

You can specify different angles either in terms of degrees or in terms of turn. The value of 1 turn is equal to 360°. This can make the calculation easier when you know how much you want to turn the elements in terms of complete rotations. The following example shows how to animate the scaling, translation, or rotation of an element on an individual basis as well as all at once.

1
var animateScaling = anime({
2
  targets: '.square',
3
  scale: 0.8
4
});
5
6
var animateTranslation = anime({
7
  targets: '.square',
8
  translateX: window.innerWidth*0.8
9
});
10
11
var animateRotation = anime({
12
  targets: '.square',
13
  rotate: '1turn'
14
});
15
16
var animateAll = anime({
17
  targets: '.square',
18
  scale: 0.8,
19
  translateX: window.innerWidth*0.8,
20
  rotate: '1turn'
21
});

SVG Attributes

It is possible to animate attributes of different SVG elements using Anime.js. The only condition is that the value of those attributes should be numerical. This ability to animate different attributes opens up the possibility of creating some really cool effects. Since you are just starting to learn about Anime.js, we will keep the examples in this tutorial very basic. As we move forward, you will learn how to create more complex animations. 

Here is the code to animate the cx, cy, and stroke-width attributes of a circle. Just like the CSS properties, you need to use a camel case version of stroke-width for the code to work.

1
var animateX = anime({
2
  targets: '.circle',
3
  cx: window.innerWidth*0.6
4
});
5
6
var animateStrokeWidth = anime({
7
  targets: '.circle',
8
  strokeWidth: '25'
9
});

DOM Attributes

You can also animate numerical DOM attributes just like you animated the SVG attributes. One situation where animating a DOM attribute can be useful is the HTML5 progress element. This element has two attributes: value and max. In our example, we will be animating the value attribute to show the progress of our file transfer process. Here is the code to animate the value attribute.

1
var animateProgress = anime({
2
  targets: 'progress',
3
  value: 100,
4
  easing: 'linear'
5
});

Dynamic Element Selection

We have now learned how to use different types of selectors to target specific groups of elements for animation. We also know how to specify the value of different CSS properties that we want to animate.

Let's use this knowledge to show a greeting to our visitors, where each word of the greeting fades in and drops down from the top. Since we want to animate each word separately, we will have to place each word within its own wrapper span tags. We have done this so far by manually creating a wrapper inside the HTML. Now, we will learn how to let JavaScript take care of the markup. Here is our heading element:

1
<h1>Have a Great Day Ahead</h1>

There are five separate words in the heading, and we will wrap each word within its own span tags. We can do that with the following JavaScript:

1
var greeting = document.querySelector('h1');
2
greeting.innerHTML = greeting.textContent.replace(/(\w+)/g, "<span>$&</span>");

Basically, we are using Regex to identify different words and then wrapping the selection within span tags. The final result is then assigned to the innerHTML of the heading element.

The heading will initially be invisible and then will fade in while dropping down. This means that the initial opacity of each span tag should be zero. Here is the CSS that we use to style our heading and span tags.

1
h1 {
2
  text-transform: uppercase;
3
  font-weight: 900;
4
  font-size: 8rem;
5
  display: flex;
6
  justify-content: center;
7
  flex-wrap: wrap;
8
  gap: 2rem;
9
  color: white;
10
}
11
12
h1 span {
13
  opacity: 0;
14
}

This is the JavaScript that we use to animate the words:

1
anime({
2
  targets: 'h1 span',
3
  opacity: 1,
4
  translateY: 100,
5
  delay: anime.stagger(1000)
6
});

We target the words using h1 span as our selector. The final value of the opacity property is set to 1, and each element moves down by 100 px from the initial position due to the translateY property. We have also used staggered delay in our animation initialization. You will learn more about staggering in Anime.js in the next tutorial of the series.

Here is a CodePen demo that shows the greeting animation we just created. Click on the Greet Me button to restart the animation.

Final Thoughts

In this tutorial, you learned about all the ways of selecting target elements in Anime.js and how to animate different CSS properties and attributes related to them. At this point, however, we are not controlling anything related to the actual animation.

In the next tutorial of the series, you will learn how to control the easing, delay, and duration of the animation for different properties as a group as well as individually. You will then learn how to control all these animation parameters for individual elements.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.