Execute JavaScript only when the page is initially loaded

Is there a way to make this code only run when the page loads for the first time?

Can I achieve something similar to IsPostBack in JavaScript?

IsPostBack: Determines if the page is being rendered for the first time or due to a postback. More info here.

<script>  

window.onload = function TimedCss()
{

    setTimeout(myTimeout1, 0500) 
    setTimeout(myTimeout2, 1000) 
    setTimeout(myTimeout3, 1500)
    setTimeout(myTimeout4, 2000) 
    setTimeout(myTimeout5, 2500)
    setTimeout(myTimeout6, 3000)
}



}
function myTimeout1() 
{
    document.getElementById("LBLName").className = " animated fadeInLeft";
    document.getElementById("LBLName").style.visibility = "visible";
}
function myTimeout2() 
{ 
    document.getElementById("LBLDescription").className = " animated rotateIn";
    document.getElementById("LBLDescription").style.visibility = "visible"; 
}
function myTimeout3() 
{
    document.getElementById("P1").className = " animated zoomIn";
    document.getElementById("P1").style.visibility = "visible";
}
function myTimeout4()
{
    document.getElementById("TXTQuantity").className = " animated flipInY";
    document.getElementById("TXTQuantity").style.visibility = "visible";
}
function myTimeout5()
{
    document.getElementById("LBLPrice").className = " animated slideInLeft";
    document.getElementById("LBLPrice").style.visibility = "visible";
}
function myTimeout6()
{
    document.getElementById("BTNAddToCart").className += " animated fadeInUp";
    document.getElementById("BTNAddToCart").style.visibility = "visible";
}

</script> 

Edit - Solution:

<script>
window.onload = function TimedCSS()
{
    var isPostBack=<%= IsPostBack ? "true" : "false" %>

    if (!isPostBack)
    {
        setTimeout(myTimeout1, 0500) 
        setTimeout(myTimeout2, 1000) 
        setTimeout(myTimeout3, 1500)
        setTimeout(myTimeout4, 2000) 
        setTimeout(myTimeout5, 2500)
        setTimeout(myTimeout6, 3000)
    }




function myTimeout1() 
{
    document.getElementById("LBLName").className = " animated fadeInLeft";
    document.getElementById("LBLName").style.visibility = "visible";
}
function myTimeout2() 
{ 
    document.getElementById("LBLDescription").className = " animated rotateIn";
    document.getElementById("LBLDescription").style.visibility = "visible"; 
}
function myTimeout3() 
{
    document.getElementById("P1").className = " animated zoomIn";
    document.getElementById("P1").style.visibility = "visible";
}
function myTimeout4()
{
    document.getElementById("TXTQuantity").className = " animated flipInY";
    document.getElementById("TXTQuantity").style.visibility = "visible";
}
function myTimeout5()
{
    document.getElementById("LBLPrice").className = " animated slideInLeft";
    document.getElementById("LBLPrice").style.visibility = "visible";
}
function myTimeout6()
{
    document.getElementById("BTNAddToCart").className += " animated fadeInUp";
    document.getElementById("BTNAddToCart").style.visibility = "visible";
}

</script>

Answer №1

Make sure to store a variable in the Cookie upon initial page load and then regularly check its value.

For guidance on using Cookie, please visit this link.

[UPDATED]

To comply with the origin-same policy of Cookie, I have created an HTML demo webpage accessible through the source code.

I've provided the following code snippet as a backup for your use. Please run the code on your own origin due to the restrictions of the origin-same policy mentioned earlier.

<!DOCTYPE>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>
        <div id="pageLoadStatus"></div>
        <script>
            var _ = {};
            /**
             * Gets or sets cookies
             * @param name
             * @param value (null to delete or undefined to get)
             * @param options (domain, expire (in days))
             * @return value or true
             */
            _.cookie = function(name, value, options)
            {
                if (typeof value === "undefined") {
                    var n, v,
                        cookies = document.cookie.split(";");
                    for (var i = 0; i < cookies.length; i++) {
                        n = $.trim(cookies[i].substr(0,cookies[i].indexOf("=")));
                        v = cookies[i].substr(cookies[i].indexOf("=")+1);
                        if (n === name){
                            return unescape(v);
                        }
                    }
                } else {
                    options = options || {};
                    if (!value) {
                        value = "";
                        options.expires = -365;
                    } else {
                        value = escape(value);
                    }
                    if (options.expires) {
                        var d = new Date();
                        d.setDate(d.getDate() + options.expires);
                        value += "; expires=" + d.toUTCString();
                    }
                    if (options.domain) {
                        value += "; domain=" + options.domain;
                    }
                    if (options.path) {
                        value += "; path=" + options.path;
                    }
                    document.cookie = name + "=" + value;
                }
            };

            var hasLoadedBefore = _.cookie('hasLoadedBefore');
            if(!!hasLoadedBefore) $('#pageLoadStatus').text('This page has been loaded before.');
            else $('#pageLoadStatus').text('This page loaded at first time.');
            _.cookie('hasLoadedBefore', true);
        </script>
    </body>
</html>

Answer №2

Keep in mind that there is no guarantee your script will only run during the initial load.

To add an extra layer of protection, consider storing data in session storage, cookies, and localStorage.

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

What could be preventing this src tag from loading the image?

Here is the file structure of my react project Within navbar.js, I am encountering an issue where the brand image fails to load from the Assets/images directory. import '../../Assets/Css/Navbar.css'; import image from '../../Assets/Images/a ...

Passing props to a click event in React JS: A comprehensive guide

I have two color circles displayed below. When a circle is clicked, the color of that circle should update the bottom icon with the same color. However, this functionality is currently not working. Is there a way to pass the addcolor props to the handleCl ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

Keep the link underlined until a different button is pressed

I need help with a webpage that displays a list of partners organized by categories. When clicking on sidebar categories, the link remains underlined. However, if you click anywhere else on the page, the link becomes inactive. CSS: button:hover { t ...

Issue with idangero.us swiper: resizing problem occurs when image exceeds window size

Having an issue where resizing my window causes the image to become larger than anticipated. As a result, the current image is partially cropped on the left side while the previous image starts to show through. Here's a description of what's happ ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Protractor - Not waiting for all elements to load before opening a popup window

Despite my efforts to ensure the stability of my test, there are instances where it does not wait for all elements within an integrated popup, resulting in failure. This particular test case is quite intricate as it involves nested if statements to execut ...

Proper date formatting in Angular Data Table

Could anyone help me with date formatting? I am facing an issue with the date format in a table within my application. The current date format is not correct and appears as shown on the screen. I would like to format it to YYYY-MM-DD only. Any suggestions ...

Develop a unique directive that embeds HTML content in a different location than where it is initially utilized

After creating an AngularJS directive, the task at hand is to insert an HTML element as a child of the body element. The challenge arises when this element needs to contain another custom component, which is defined as a directive. My initial attempt invo ...

Create an array using the counted elements of another array using JavaScript/jQuery

Hi there, I have a question that has been perplexing me. I am attempting to create raw data for a chart. Imagine I have an array like this: [1,0,0,1,2,0] Is there a method to transform this into an array with nested arrays representing the count ...

Tips for obtaining images and displaying them using Node.js

Trying to obtain an image and display it on a URL using the request module. For instance, aiming to fetch the image https://www.google.com/images/srpr/logo11w.png, and show it on my URL http://example.com/google/logo. Alternatively, displaying it with &l ...

Navigation and Cart Menu Issue: Inability to Expand or Collapse

The website I am currently working on is . I'm facing an issue where the cart menu expands but cannot collapse and the navigation menu does not expand when I resize the window for mobile view. Everything works fine in the normal view of the window. Ho ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Alter regular expression matches within the new string replacement

I am having an issue with using regex to extract URLs from a text and then modifying all the matches within the replacement string using a function. Below is a simplified example of what I am trying to accomplish. Is it possible to achieve something lik ...

Incorrect arrangement of divs upon browser launch

Utilizing javascript/jquery, I am arranging a series of divs within a larger div: this.inputArea.append(newItem); In this code snippet, inputArea represents the jquery object of the container div, and newItem refers to the corresponding object of the div ...

Approach to Methodology - JSON data/result

Just testing the waters with this question for SO. It's my first time posting, and I'm hoping to get some guidance on how to tackle a task that has been assigned to me. I currently have a page with a form containing some basic fields set up. Th ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Combining array outputs from both Promise.all and map functions

Hey, it might seem silly, but it's late and I'm struggling with this issue. My goal is to gather statistics for different types of values and store them in an array. However, the problem lies in the final result: // Data this._types = [{ id: 1, ...

Mongoose parameters do not accept passing an id or element

When working with MongoDB and using mongoose, I attempted to remove an item from a collection by utilizing the findByIdAndDelete() method. However, I encountered the following error: CastError: Cast to ObjectId failed for value "5f080dd69af4c61774ef447f" a ...

Error in Google Tag Manager: Expecting primary expression

I am encountering an issue that reads: Error at line 5, character 2: Parse error. primary expression expected This is the format of the custom HTML code: <script type="text/javascript"> //insert your Tawk embed code here, without Script tags < ...