Transitions and JavaScript

So far we’ve been using the transition property in CSS to animate between two states, a non-hover and a hover (or focus) state.

These transitions have required hovering over the element. This isn’t the only way we can trigger animations, so today we’ll cover two ways we can use JavaScript to achieve the same result.

Add or remove classes

Since the power of transitions is to animate between two states, we can create those states as separate classes. Then we add or remove these classes using JavaScript.

Source: http://codepen.io/donovanh/pen/YPbxqa

This example consists of a button and a content div. Initially the content container has the class hide. In the CSS, the hide class gives it an opacity of 0.

We also have a second class in the CSS called show. This class has an opacity of 1.

When the button is clicked, we toggle the class of the div between hide and show. To give it animation, we apply a transition to the div also.

See it in action on this CodePen.

If you’d like to read more, you might enjoy the article, Adding Appeal to Your Animations on the Web.

Toward the end of this course we’ll look into how we can trigger transitions and animations on scroll.

Controlling transitions with JavaScript

We can go further than adding or removing classes. Using JavaScript we can set the CSS properties directly like so:

  1. element.style.transition = 'opacity 1s ease-out';

In this case, “element” is an element we’ve selected. For example, if an element has the ID “js-show”, you could apply a transition to it using getElementById:

  1. document.getElementById('js-show').style.transition = 'opacity 1s ease-out';

When we do this, we must remember to include vendor prefixes too. The above would need to be written:

  1. document.getElementById('js-show').style.webkitTransition = 'opacity 1s ease-out';
  2. document.getElementById('js-show').style.transition = 'opacity 1s ease-out';

Here the webkitTransition applies to any browsers that would otherwise use the -webkit- prefix in CSS.

Let’s recap

In this chapter we’ve covered the transition property. We learned we can use this property to tell a browser to animate from one state to another.

Transitions and JavaScript - 图2

Along the way we’ve learned about the various properties: duration, delay, and timing functions.

Putting these together we can create interesting combinations of effects, and even apply multiple transitions to a single element.

Finally, we wrapped it up today by covering how to apply these transitions using JavaScript.

Transitions are but one part of the CSS Animation puzzle. Next we’ll cover the animation property.

Homework

Before we start looking at the animation property, take some time to think about how you use transitions.

Can you think of ways they could help smooth the interactions or state changes on your pages? How might they add appeal?