Transitions and JavaScript

    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.

    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.

    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 . 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 also.

    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.

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

    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:

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

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

    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 property.

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