I'm interested in clicking on an image within a div to trigger a page refresh and then automatically hide the div once the page has refreshed

UPDATE 2

SITUATION

To prevent access to quiz content until the page is refreshed, I am employing a semi-transparent image with a top-margin off-set.

The following code functions flawlessly on one specific page and only once:

JavaScript

window.addEventListener('DOMContentLoaded', (event) => { //document ready event
  const question1Elm = document.querySelector('#question-1');
  const question1Clicked = window.localStorage.getItem('question1Clicked');
  
  if (question1Clicked) { 
    question1Elm.classList.add('quiz-lock-d-none');
  } else {
    question1Elm.classList.add('quiz-lock');
    question1Elm.addEventListener('click', (event) => {
      window.localStorage.setItem('question1Clicked', '1')
      window.location.reload();
    });
  }
});

CSS

.quiz-lock img {
  margin-top: -235px;
}
.quiz-lock img:hover {
    margin-top: -235px;
    cursor: pointer;
}
.quiz-lock-d-none {
  display: none;
}

HTML

[quiz shortcode]
<span id="question-1" class="quiz-lock">
<img src="images/lock-panel.png" />
</span>

There are 57 sections each with a pre and post quiz. Users can complete multiple sections in one session. The quiz lock functionality needs to work independently for each section page.

I attempted to implement naveen's method for handling multiple elements, resulting in the following code:

window.addEventListener('DOMContentLoaded', (event) => { //document ready event
  const question1Elm = document.querySelector('#question-1');
  const clickedQuestions = JSOn.parse(localStorage.getItem('clickedQuestions')); 
  
  if (question1Clicked) { 
    question1Elm.classList.add('quiz-lock-d-none');
  } else {
    question1Elm.classList.add('quiz-lock');
    question1Elm.addEventListener('click', (event) => {
      window.localStorage.setItem('clickedQuestions', JSON.stringify([1, 3, 5))
      window.location.reload(); 
    });
  }
});

However, this modification completely disrupts the functionality. It is evident that I have made an error somewhere.

Thank you for your assistance.

Answer №1

To maintain a value across page reloads, you can utilize either sessionStorage / localStorage

Pseudo Code

HTML

<span id="question-1" class="quiz-lock">
    <img src="https://dummyimage.com/200x40/fff/aaa"/>
</span>

JavaScript

window.addEventListener('DOMContentLoaded', (event) => { //document ready event
  //question element (to show/hide)
  const question1Elm = document.querySelector('#question-1');
  //localStorage element that retrieves the item with key question1Clicked
  const question1Clicked = window.localStorage.getItem('question1Clicked');
  //check if localStorage contains item with key question1Clicked
  if (question1Clicked) { 
    //if it exists, hide the element
    question1Elm.classList.add('quiz-lock-d-none');
  } else {
    // if not found, display the element
    question1Elm.classList.add('quiz-lock');
    question1Elm.addEventListener('click', (event) => { //span click event
      // set localStorage item, key=question1Clicked, value=1
      window.localStorage.setItem('question1Clicked', '1')
      window.location.reload(); //reload the page
    });
  }
});

CSS

.quiz-lock {
  margin-top: -235px;
}

.quiz-lock-d-none {
  display: none;
}

For multiple elements, apply the same logic in a loop and store the clicked questions in an array in localStorage to manage show/hide classes.

Set:

window.localStorage.setItem('clickedQuestions', JSON.stringify([1, 3, 5))

Get(if item exists):

const clickedQuestions = JSOn.parse(localStorage.getItem('clickedQuestions')); //array

P.S: Leveraged JSON.stringify and JSON.parse as setItem only accepts DomString for key and value

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

I'm having trouble figuring out how to perfectly center this div on all types of devices

As someone who is new to css, I have been struggling to center these divs in the middle of the page across all devices despite searching extensively online and trying various solutions without any success. Check out my code below: Snippet: :after, :be ...

Enhance VideoJS using custom Ionic icons in a NextJS environment

I'm creating a platform for video content and I want to enhance the VideoJS player by incorporating icons from the Ionic set. However, as I typically use the <ion-icon/> tag to insert icons on my pages, I had to individually specify each icon&ap ...

What causes the TypeError: 0 is not a function error when using Array.from as a callback for Array.flatMap?

An issue arises when using Array.from as a callback with Array.flatMap, resulting in the error message: "TypeError: 0 is not a function" const x = ["12"].flatMap(Array.from) console.log(x) However, when used as a regular function, Array.from operates n ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

Looking for assistance with CSS to properly align a dozen items

UPDATE: See the current layout in this JFiddle based on feedback received from others, still a few tweaks needed. In my setup, there are 12 divs housed within one container div. These 12 divs consist of 6 text components and 6 corresponding input fields. ...

jQuery: automatic submission on pressing enter compared to the browser's autocomplete feature

Here is a JavaScript code snippet that automatically submits the form when the user presses the "enter" key: jQuery.fn.installDefaultButton = function() { $('form input, form select').live('keypress', function(e) { if ((e.which && ...

What is the reason for the failure of this code to store data in local storage (undefined)?

After creating a new div with data from an input form, I noticed that the first div properly saves the inputted data. However, when I try to input new data, the div displays an undefined value. first attempt second attempt 0: {name: "Milk", amount: "30"} ...

Position two in-line divs at the bottom, one on each side

I am in search of a way to dynamically position two elements at the bottom of a container, making sure they are at opposite corners. Much like how the Stackoverflow Logo and the Ask Question are aligned at the bottom but on different ends of their containe ...

I'm having trouble with my dropdown menu functionality

My dropdown menu was functioning properly until yesterday, and now I am unable to determine what went wrong even after double-checking the code. #apDiv2 { position: fixed; width: 100%; height: auto; float: none; z-index: 6; list-style-type: ...

`How can I manage my electron.js application effectively?`

As a newcomer to electron.js, I have successfully created a game using html, css, and javascript that currently runs offline on the client side. However, I am now looking for a way to access, analyze, and make changes to this app. One solution could be lo ...

Tips for formatting angular text sections

Within the scope of a controller, I have a status variable. After a successful rest PUT request, I add a message to this JavaScript variable. This message is displayed in my template using the {{status}} Is there a way to customize the styling of this mes ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

Tips for concealing a parent element while inside a span with jquery

Beginner asking for help! Take a look at what I've coded: <div class="Links"> <a href="/testthis1.html" data-id="button1"> <img class="icon" src="/test1.png" alt="test1"> <span>Test 1</span> < ...

When the ng-model is updated within a promise's .then() function, the ng-change

I've encountered an issue with ng-change in a select not triggering when I update the ng-model parameter within my promise.then function. Here's my select code: <select ng-model="currentReport" ng-options="rpt.ReportDisp for rpt in availa ...

Is there a way to use regular expressions to search for class names within nested div elements?

I'm struggling to find nested divs like these in my document object model (DOM) <div class="two-columns some-other-class"> <div class="two-columns some-other-class"> </div> </div> I attempted to search for neste ...

The sequence of indices in a for loop and making Ajax requests

I'm dealing with a challenge related to executing ajax requests within a for loop. Despite researching solutions online and implementing them to prevent synchronous request execution, I still face an issue in maintaining the correct order of the succe ...

What are the steps for adding information to a MySQL database with GWT, HTML, and either JDBC or Hibernate?

I have been working with GWT (Google Web Toolkit) version 2.5.1 and successfully developed a sample application to display the username and password. However, I am now facing challenges in inserting these values into a MySQL database table using JDBC or Hi ...

Is there a way to use setTimeout in JavaScript to temporarily stop a map or loop over an array?

data.forEach((d, i) => { setTimeout(() => { drawCanvas(canvasRef, d); }, 1000 * i); }); I have implemented a loop on an array using forEach with a one-second delay. Now I am looking to incorporate a pause and resume f ...

Using React JS to extract query string values

My current URL contains the following: http://example.com/callback?code=abcd I am trying to extract the value of "code." Here is the React code I have written: import React from 'react'; import { useEffect } from 'react'; const Callba ...