DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Running CSS Animations Once Per Session
Gabe
Gabe

Posted on

Running CSS Animations Once Per Session

I was working on some intro animations the other day for my site and had an idea to have a user land on the homepage, and the word β€œhello” would slide in from the left greeting them.

The animation bit was reasonably straightforward, I used CSS animations to translate the text’s X value from -100% to zero. When testing the animation, I got what I wanted; the text now slid in from the left.

@keyframes slideInFromLeft {
    0% {
        transform: translateX(-100%);
    }

    100% {
        transform: translateX(0);
    }
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

There was a problem though, every time I refreshed the page, the animation would replay, this got pretty annoying when navigating through the site and returning home. So I decided to use some JavaScript and the Window's session-storage property to solve my problem.

For those who may be unfamiliar with the session-storage property: think of it like local-storage. With local-storage, we can store data that won't expire. The difference with session-storage is that the data expires after the window or browser tab is closed.

I started with an if statement that read something like β€œIf a property called animated within the session-storage property is equal to null, run the following code”

if (window.sessionStorage.getItem(β€˜animated’) === null) {} 
Enter fullscreen mode Exit fullscreen mode

Within that if statement code block, I targeted the text that would be animating, added the β€œanimate” class to it, which contained the CSS animation rule, and then set the animated property within session-storage to 1.

if (window.sessionStorage.getItem(β€˜animated’) === null) { 
    document.getElementById(β€˜my-text’).classList.add(β€˜animate’);
    window.sessionStorage.setItem(β€˜animated’ ,1);
} 
Enter fullscreen mode Exit fullscreen mode

And now, the animation only fires once per session. A quick and easy way to ensure we don’t annoy our users with our fancy animations.

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await