Play CSS Animation Only Once Per Website Visit
In JavaScript Nov 15, 2021
Updated on May 22, 2023
We have animated elements in the hero section of our website, but we do not want to play this animation all the time our users return to the home page where this hero section is. We want to play this CSS animation only once, when the user enters the site, and never again during the current session. How can we achieve that?
Create the Project
Let’s create our project folder! Let’s name it “animation”. From the terminal we type:
mkdir animation
Let’s change the directory to this project folder:
cd animation
In our project, we will create three files: index.html
, index.js
, and
index.css
.
Write the HTML Code
Now, let’s open the index.html
file and add this code:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Animation</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1 id ="heading" class="animated">Animated Heading</h1>
<script src="index.js"></script>
</body>
</html>
We have a simple document, with only a heading. We've added an “animated” class to this
<h1>
element. The elements with that class will be animated, according to the rules we’ll set in
the index.css
file. After the first page load, when the animation has run once, we’ll remove that class
name from the element, so that animation won’t play again during the session. We set a “heading” id for this element,
so we can select it via JavaScript.
Write THe Animation
Let’s now open our index.css
file, to write our animation. It’s a simple animation, the
<h1>
element will be hidden at first, then will come from the top and land in its normal
position.
We’ll call this animation “moveIn”. Let’s specify the CSS rules inside the @keyframes
rule:
@keyframes moveIn {
0% {
opacity: 0;
transform: translateY(-3rem);
}
100% {
opacity: 1;
transform: translate(0);
}
}
Now, we apply this animation to the elements that have an “animated” class:
.animated {
animation: moveIn 1.5s ease-out;
}
Write the JavaScript Code
Now, when we open our page, the animation will play. If we refresh the page, the animation will play again. To prevent
this, we need to write some JavaScript. Let’s open the index.js
file!
We want to store an item in the sessionStorage
that reminds the browser that our heading has already been
displayed to the user, and the animation has run.
We’ll call this item “Heading” and its value will be “displayed”. We do this as soon as the page is loaded:
window.addEventListener('load', () => {
if (document.querySelector('#heading') !== null) {
window.sessionStorage.setItem('Heading', 'displayed');
}
})
Then we write another function that checks if this item is present in the sessionStorage
, select our
heading, and remove the class “animated” from it.
if (window.sessionStorage.getItem('Heading')) {
document.querySelector('#heading').classList.remove('animated')
}
From now on, the heading will remain in its normal position, and the animation will not play again.