Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words

"Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site.

However, there is an issue when users decide to return back to the main page - the animation plays again. To rectify this, I simply want the text "Hello. I'm Bob" displayed without any animation effect.

$(".fade-in-first").addClass("animated fadeInUp");
setTimeout(function(){
     $(".fade-in-second").animate({ opacity: 1 });
    $(".btn-explore").addClass("pulse-anim");
}, 1300);

The jQuery code above controls the animation sequence. Ideally, I would like to implement a condition such as ...

if (count) == 0, then animate, count ++

Despite my attempts at using variables to achieve this, I encountered difficulties in implementing the desired functionality.

Answer №1

One way to keep track of whether a user has viewed the animation is by utilizing localStorage.

Regarding the setTimeout function used in the code snippet, I have some reservations about it, but I'll leave it as is.

$(".fade-in-first").addClass("animated fadeInUp");
setTimeout(function(){
  if(typeof(localStorage.getItem("welcomeShown")) != null && localStorage.getItem("welcomeShown") != "true"){
    $(".fade-in-second").animate({ opacity: 1 },5000);
    localStorage.setItem("welcomeShown","true");
  }else{
    $(".fade-in-second").css("opacity", 1);
  }

  $(".btn-explore").addClass("pulse-anim");
}, 1300);

If you want to experiment with this code, feel free to check it out on CodePen. There's even a button provided to clear the localStorage for multiple trial runs!

Answer №2

If the user's browser reloads your site upon returning to the homepage (not a single-page app), your scripts will reset as well, causing the count value to be lost. This value is essential for tracking the user's previous visit.

To address this issue, you can either use a cookie, or utilize either sessionStorage or localStorage.

// sessionStorage or localStorage (both work the same way)
if (!sessionStorage.getItem('hasVisited')) {
  $(".fade-in-first").addClass("animated fadeInUp");
  setTimeout(function(){
    $(".fade-in-second").animate({ opacity: 1 });
    $(".btn-explore").addClass("pulse-anim");
  }, 1300);

  sessionStorage.setItem('hasVisited', true); 
}

Use sessionStorage if you only need to track their homepage visit for the current session. The stored data is available until the tab, window, or browser is closed. Note that sessionStorage behavior may vary across tabs due to how browsers handle tab history.

Choose localStorage if you want the value to persist across different sessions and tabs. All browsing tabs on your site share the synchronized localStorage object.


Note 1: It's advised to manipulate values in the Web Storage API (session/localStorage) using setItem() / getItem() to prevent issues with inherited prototype values and accidental property overwrites.

For instance:

localStorage.key = 'My key value';
console.log(localStorage.key);

In the above scenario, the assigned value is accessible but inadvertently replaces the key method of the localStorage object!


Note 2: These values are limited to the same subdomain and protocol! Crossing subdomains or protocols won't retain the information from www.example.com to login.example.com, or transitioning between http://www.example.com and https://www.example.com.

Cookies

Cookies offer an alternative solution, although parsing values requires more effort (especially when already using jQuery). Pay attention to set the appropriate path for the cookie's scope and consider the expires attribute. Refer to these resources for additional details:

https://www.w3schools.com/js/js_cookies.asp

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Answer №3

An alternative approach that offers more flexibility, especially if you need to account for multiple visit scenarios.

if (!localStorage.hasVisited) {
    localStorage.hasVisited = true;
} else if (localStorage.hasVisited == 'true') {
    localStorage.hasVisited = false;
}

if(localStorage.hasVisited == 'true') {
    $(".fade-in-first").addClass("animated fadeInUp");
    setTimeout(function(){
        $(".fade-in-second").animate({ opacity: 1 });
        $(".btn-explore").addClass("pulse-anim");
    }, 1300);
}

Answer №4

One way to prevent replaying an animation on a specific page is by utilizing LocalStorage to set an attribute indicating that the animation has been loaded. However, this approach has its drawbacks as the user will not be able to see the animation again until they clear their LocalStorage.

An alternative approach, which I personally find better, is to use cookies with a short expiration time, such as 1 day.

Here's an example using localStorage:

// Play the animation only once using LocalStorage
if (!window.localStorage.getItem('homeAnimPlayed')) {
    setTimeout(() => {
        window.localStorage.setItem('homeAnimPlayed', "true");
        this.setState({ animationLoaded: true })
    }, 3000);
} else {
    this.setState({ animationLoaded: true })
}

And here's how you can achieve the same result with a cookie:

// Set a cookie to play the animation only once with 1-day expiration

function writeCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// Use these functions to read/write cookies with custom expiration dates
let cookie = readCookie("animPlayed_home");
if (!cookie) {
    setTimeout(() => {
        writeCookie("animPlayed_home", "true", 1);
        this.setState({ animationLoaded: true })
    }, 3000);
} else {
    this.setState({ animationLoaded: true })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Height of list items in image gallery does not automatically readjust

I'm facing an issue regarding the height of an li element. Check out this CodePen link for reference. <div class="row fp-gallery"> <ul class="large-block-grid-4 medium-block-grid-4 small-block-grid-2"> <li> <a href= ...

Issue with the formatting of the disabled button

I am facing an issue with styling a disabled button. Whenever I try to apply custom styling, it reverts back to the default styling. I have already cleared my cache but the problem persists. The button is disabled using JavaScript with document.getElementB ...

Deleting query strings from the URL - HashRouter

In my application, I have a LoginContainer component that houses both a login-form and a signup-form. These components are displayed on the same page, with only one of them being rendered based on user interaction. While the functionality of the forms is ...

Is there a way to bypass the default layout on app router in Next.js and implement our own custom page layout

Utilizing a default layout in layout.jsx, I passed all my other pages as children through props. In the page router, we typically configure the router path to specify which layout to use. However, in this new system, I am facing challenges with coding it. ...

Can you explain the purpose of this function on Google PlusOne?

Within the code snippet below: (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByT ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

Submit Button Not Responding on Mobile Device

I am facing an issue with my VueJs app. The contact form works perfectly on browsers, but when accessed from a smartphone or tablet, it fails to function properly. I have tried two different implementations to resolve the problem. Here is the first implem ...

Using an external HTML file to import a template into Vue.js single file components

I've been tackling a Vuejs project that involves using vue-property-decorator in single file components. I'm trying to figure out how to import the template from an external HTML (or different) file, but so far I haven't found a solution. I& ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Code executing twice instead of once in Javascript

Having trouble with a script in my demo below. When I enter "first input", submit, then click on the returned "first input", it alerts once as intended. However, upon refresh, if I enter "first input", submit, then add "second input", submit, and finally c ...

Encountering a ValueError when attempting to validate form fields with Django and JavaScript

I encountered an error while trying to validate a field using Javascript and Django. Error: ValueError at /insert/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: ...

file_put_contents - store user-defined variables

When I execute this script, it successfully generates the html page as expected. However, I am encountering challenges in incorporating variables, such as the $_GET request. The content is enclosed in speech marks and sent to a new webpage on my site usin ...

What occurs when socket.io events are not properly handled?

Is socket.io ignoring or dropping messages? I am asking this because there is a client with multiple states, each having its own set of socket handlers. The server notifies the client of a state change and then sends messages specific to that state. Howeve ...

Vue.js - Exploring methods to append an array to the existing data

I am looking to structure my data in the following way: Category 1 Company 1 Company 2 Company 3 Category 2 Company 1 Company 2 Company 3 Below is my code snippet: getlist() { var list = this.lists; var category this.$htt ...

Challenges in accurately selecting jQuery elements

Currently on my test page, the display is showing Test Page, which indicates something is appearing, but not in the right manner. I have these jQuery Objects: reviews: Array[3] 0: Object excerpt: "Everything I have had here is insane. SO GOOD. I ...

What is the best way to access a DOM node within a withStyle component?

Currently, I am involved in a react project where my team and I are utilizing Material UI. I encountered a situation where I needed to access the DOM node of another component that was wrapped by a HOC. To achieve this, I attempted using ref in React but o ...

Expo BarCodeScanner becomes unresponsive (specifically, the camera) upon exiting the application

I am using Expo's BarCodeScanner component within a tab: return ( <View style={{ flex: 1, flexDirection: "column", justifyContent: "flex-end", }} > <BarCodeScanner onBarCodeScanned={s ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...

Accessing props in react-native-testing-library and styled-components is not possible

I defined a styled-component as shown below: export const StyledButton = styled.TouchableOpacity<IButtonProps> height: 46px; width: 100%; display: flex; flex-direction: row; justify-content: center; align-items: center; height: 46px; ...

What is the best way to eliminate all frames from the current windows using jQuery?

When transitioning to another page from my center frame, I need to ensure that the top and bottom frames are not visible in the new page. This will prevent my spinner or footer from showing up on the page I'm navigating to. Is it possible to achieve ...