How can I save a value in JavaScript once the page has finished loading?

$("#divid1").click(function(){
    $("#divid1").hide(); //this should remain hidden even after refreshing the page
    $("#hideid1").hide(); //this should remain hidden even after refreshing the page
    $("#id1").show(); //this should remain visible even after refreshing the page
});
.hide{
    display:none; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/img/done.png"  id="divid1" alt="divid1"/>
<img src="/img/schedule.png" height="12" width="12" id="hideid1" alt="hideid1" />
<div id="id1" class="hide"><img src="/img/done.png" height="12" width="12" alt="id1" /></div>

My goal is to display an image after the page loads, and when clicking on it, show a new image while hiding the old one. However, this setup resets upon refreshing the page.

I would greatly appreciate a solution to maintain the desired behavior even after page refresh.

An implementation using my specific IDs would be most helpful! Thank you!

Answer №1

Utilize localStorage.

Add item

localStorage.setItem('selectedId', 100);

Retrieve item

localStorage.getItem('selectedId');

Delete item

localStorage.removeItem("selectedId");

Illustration

$(document).ready(function(){
    //Function for events
    function dummyFunction(){
        $("#divid1").hide(); //keep hidden after page refresh
        $("#hideid1").hide(); //keep hidden after page refresh
        $("#id1").show(); //keep showing after page refresh
    }
    //Check localStorage value
    if(localStorage.setItem('itemClicked') == 1)
    {
       dummyFunction();
    }
    //Div click event
    $("#divid1").click(function(){
        dummyFunction();
        //Set localStorage
        localStorage.setItem('itemClicked', 1);
    });
});

Answer №2

Take a look at the Example. This demonstration should provide clarity.

Javascript

$("#divid1").click(function(){
   $("#divid1").hide(); //aiming for sustained concealment after page refresh
   $("#hideid1").hide(); //intending for lasting concealment after page refresh
   $("#id1").show(); //desiring continuous visibility after page refresh
   localStorage.setItem('hidden', true);
});

$(function() {
   // if hidden attribute in localStorage is set to true, apply hiding and showing logic
   if(localStorage.getItem('hidden')){
     $("#divid1").hide(); 
     $("#hideid1").hide(); 
     $("#id1").show();
   }
});

Answer №3

One solution is to utilize cookies to trigger the same action as if the user manually clicked on page load.

Unfortunately, aside from that workaround, there aren't many options available. The page refresh serves to reset the JavaScript functionality of a webpage.

Answer №4

If you're facing an issue, this code snippet might be just what you need. Simply add it to the load event and watch your problem disappear.

$(window).load(function(){
    $("#divid1").hide(); 
    $("#hideid1").hide();
    $("#id1").show(); 
});
.hide{
    display:none; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/img/done.png"  id="divid1" alt="divid1"/>
<img src="/img/schedule.png" height="12" width="12" id="hideid1" alt="hideid1" />
<div id="id1" class="hide"><img src="/img/done.png" height="12" width="12" alt="id1" /></div>

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

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...

Struggling to change the div content with ajax response transmitted through php

I would like to apologize in advance if this question has already been addressed elsewhere. After conducting a search, I came across several relevant posts that have guided me to this point. Below is the form snippet containing 1 input box, a button, and ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

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. ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

The "apply" function in Javascript cannot be found in the window.external extension object

Utilizing the javascript extension (known as window.external) in IE8 (or any IE version) to expose specific functions, I encountered an issue when attempting to call the apply function. Despite the belief that it is inherently available in every JS functio ...

Trouble with firing the click event using document.createElement('a') in Firefox

I wrote a function that fetches arraybuffer data from my API, generates a temporary anchor element on the webpage, and then triggers a click event to download the file. Interestingly, this function performs as expected in Chrome. @action async loadVouc ...

Tips for displaying an image larger than its container using CSS or Bootstrap

I'm attempting to include an image on the left side of text within a dark container. However, I want the picture to start at the very bottom of the container and extend above the top of the container, so that the image appears outside the top of the c ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Looking for assistance in determining a solution for progress bar implementation

Currently, I am developing a simple application using web technologies like HTML, CSS, and jQuery Mobile. This app enables me to create goals and save them to a listview using the <li> element. Every <li> representing a goal will have an assoc ...

The addition of an asynchronous call caused Array.map to start experiencing errors

I am working on a React component that iterates through an array of messages and renders JSX based on certain conditions: messages.map(async (msg) => { let previewImage: URL | undefined = undefined; if (msg.mediaId) { previewImage = await stora ...

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

Accessing a JBoss Web Service using JavaScript (AJAX) - A Comprehensive Guide

After experimenting with JBOSS's Web Services, I have successfully set up the following: http://127.0.0.1:8080/IM/TestService?wsdl My next challenge is to call Web Methods from that Web Service using JavaScript. For example, if there's a web m ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Create a one-page website that utilizes the jQuery load() function

I'm interested in creating a single-page website with top navigation, left sidebar, and a #content div for content exchange. $(document).ready(function() { // or click on a button $('#content').load('somepage.php'); }); <scrip ...

Begin highlighting the columns in the table with color starting from the Nth column onwards using the td

Is there a more efficient way to apply a specific background color to multiple columns in a table without using a CSS class for each column? I have a large table with many rows and columns, and I want to minimize unnecessary code. Currently, I am utilizi ...

What is the best way to ensure uniform height and width of images within a thumbnail in Bootstrap?

I am struggling to maintain consistent image sizes within my Bootstrap gallery. How can I ensure all images are uniform in both height and width? You can view the code on jsfiddle- here. Apologies for the lack of image visibility as I'm currently wor ...

Mastering CSS: Optimizing Div Placement Across Sections

I am currently working on developing a sleek and modern landing page with multiple sections, each designed to catch the eye. This style is all the rage at the moment, featuring large headers, ample padding, bold text, and a visually appealing divider betwe ...

How can I retrieve and process a text or .csv file that has been uploaded using Multer?

Just starting out with Multer - I created an application to analyze a .csv file and determine the frequency of each keyword and phrase in the document. However, I have since made adjustments using node and express to analyse the file AFTER it has been subm ...

App.post is returning a set of empty curly braces as the response

I am currently working on an express.js application that retrieves data from a MySQL database and displays it on the screen. I am also trying to implement an insert functionality so that I can add data to the database via the browser. However, when I post ...