CSS Animation 101 Transitions and JavaScript
CSS Animation 101 Transitions and JavaScript
CSS Animation 101 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.
47
Figure 10.1: Source: http://codepen.io/donovanh/pen/YPbxqa
48
Controlling transitions with JavaScript
We can go further than adding or removing classes. Using JavaScript we can set
the CSS properties directly like so:
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:
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:
document.getElementById('js-show').style.webkitTransition = 'opacity 1s ease-out';
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.
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.
49
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?
50