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

What is the best way to retrieve the UTC value of a specific date and time within a particular time zone using JavaScript?

I want to create a Date object with a specific time: "Midnight in Los Angeles on Christmas 2011". Although I've used moment.js, which is good, and moment-timezone, which is even better, neither the default Date class nor moment constructors allow for ...

Angular Material Spinner with Custom Image Icons - (mat-spinner)

I have successfully implemented the mat-spinner in my project with configurable changes like color and mode of spinning. However, I am now looking to add an image icon, specifically the logo of a brand or company, inside the spinner. How can I achieve this ...

The disappearance of HTML DOM nodes event

When I relocate certain DOM nodes from one context to another, some of the child nodes end up losing their event listeners. HTML <div><lots of nested nodes .../><div> <div> <div> <div#newNode></div> < ...

Encountering installation issues with Next.js and experiencing a package failure with react.js during the installation process

Issue: Error encountered during Next.js installation, multiple installation failures reported including missing packages peema@DESKTOP-6UGCO8V MINGW64 ~/Documents/alert/peeapp $ next build The module 'react' was not found. Next.js requires that ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

What is the best way to expand the width of a table cell in a React + Material project?

Currently, I am utilizing material UI in conjunction with React to display my data in a table format. Within the table, there are specific titles such as "GENERAL_INFORMATION" and "INFORMATION" that I intend to center align. However, I have encountered an ...

What is causing the Access-Control-Allow-Origin error when using axios?

I have a simple axios code snippet: axios.get(GEO_IP) .then(res => res) .catch(err => err); In addition, I have configured some default settings for axios: axios.defaults.headers["content-type"] = "application/json"; axios.defaults.headers.common. ...

Obtain the dimensions of the outermost layer in a JSON file

Could you please help me extract the dimensions (600*600) of the outermost layer from the JSON below dynamically? { "path" : "shape\/", "info" : { "author" : "" }, "name" : "shape", "layers" : [ { ...

Incorporate a hanging indent within the text enclosed by the <li> element

(revised multiple times to enhance clarity) Disclaimer: I did not create the HTML code. Below is the structure of the HTML (please note that the links and text following them are on the same line): <li> <strong>Heading of section</str ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

"Interactive feature allowing users to edit and view the most recently inserted HTML

My approach involves using a contenteditable div as an input field for entering text and inserting icons through a button that adds small HTML pictures within the text. Everything works fine when the text is narrower than the contenteditable field. Howev ...

How can I implement a jQuery slide down effect for a specific individual instance?

Whenever I click on the "Share your thoughts" button, the comments block slides down for every section instead of just the particular section I clicked on. Is there a way to make it so that only a single block slides down when the button is clicked, regard ...

Replace Jade script with block override

Having trouble overriding a Jade script. tag, nothing seems to work. Here is the code snippet: Layout.jade block foot footer.container#footer .row .twelve.columns All rights reserved. &copy; 2015 Pet Feeder block scripts ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

A fading transparency box on the border

Looking for a box with varying opacity from left to right (See image for reference - the red marked box has decreasing opacity from right to left). Here is my attempt: .waterMark { background-color: #FFFFFF; float: right; opacity: 0.6; position: ...

What is the best way to extract data from a JavaScript object received from multer?

Currently, I am facing an issue while trying to utilize multer for handling the upload of a CSV file in Express. The goal is to parse the uploaded file line by line. Although I can successfully retrieve the file as an object stored in req.body, I encounter ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

Exploring the font variables in the asset pipeline of Rails 7

Creating a habit of defining a set of root variables is crucial for maintaining consistency throughout an application. :root { --main-font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; --kbd-font-family: Consolas, "Libe ...

What is the best way to incorporate CSS styles into a PHP loop?

Struggling to implement CSS styles on a PHP loop: <h3 class='title'></h3> The CSS style doesn't seem to be taking effect: .title{ color : red; } I attempted surrounding the echo with <?php ?> tags and then applying ...

The hyperlink element is failing to load in a particular frame

I've been attempting to load the URL of an anchor tag in a specific frame. I've tried various methods through online searches, but have not found a satisfactory solution. Can someone please assist me with how to load the href URL in a particular ...