Categories
Animation CSS JavaScript Web development

Animation on page load

To bring a webpage to life, you may want to start an animation when the content of the page appears. For example, a text or an image fades in, or moves to certain position, or grows to a certain size, etc.

Animation kick-off

Here is a basic method to kick off a page load transition, using JavaScript to change the classList property of the root element, which then results in changing the style of an element.

Step by step

First, add a one-line script in the head of the document that adds the class preparation (for instance) to the root element, <html>.

JS

We’ll use this class to style the begin state of the animated element. It is important that the change of the class list is executed before any content is rendered, so the element is styled to the begin state of the animation before it appears on the screen.

Say we want an article to simply fade in. We set opacity to zero for the begin state:

CSS

Here is the CSS for the end state and the transition:

CSS

We just need to remove the class preparation from the html tag, and the show begins!

JS

Degrading gracefully

If JavaScript is not available, the element class list is not affected. In that case the preparation of the animation is skipped and the user will just see the end state.

The same is true if the classList API is not available (IE11).

If JavaScript and classList are available the following – somewhat simpler – approach would give the same result as above:

CSS
JS

In the absence of JavaScript though, the user would never get to see the content.