Saving current class information in the browser's localStorage

Is there a way to store the active class of a clicked link in localStorage so it remains even when navigating to another page?

<div id="collapse2" class="panel-collapse collapse">
  <ul class="list-group">
    <li class="list-group-item active" style="background-color: #394263; color: white"><a id="a" style="color: white">A</a></li>
    <li class="list-group-item" style="background-color: #394263; color: white"><a id="p" style="color: white">P</a></li>
    <li class="list-group-item" style="background-color: #394263; color: white"><a id="s" style="color: white">S</a></li>
  </ul>
</div>

Answer №1

Assign a unique identifier to each list item.

<body onload = "check_storage()">
<div id="collapse2" class="panel-collapse collapse">
<ul class="list-group">
  <li class="list-group-item active" id="id1" onclick= "active("id1")"><a id="a" style="color: white">A</a</li>
  <li class="list-group-item" id = "id2" onclick = "active("id2")"><a id="p" style="color: white">P</a></li>
  <li class="list-group-item" id = "id3" onclick = "active("id3")"><a id="s" style="color: white">S</a></li>
</ul>
</div>

Implement a JavaScript function to store the selected id in local storage.

//This function will be called when the page loads
 function check_storage() {
    //Check if there is any stored value in localStorage
if (localStorage.getItem("listId") != null) {
    //Retrieve the stored value
    var val= localStorage.getItem("listId");
    console.log(val);
    setActive(val); //Call the function to set as active
     }
     }

 function active(id) {
localStorage.removeItem('listId');//Clear previously stored data
localStorage.setItem("listId", id);//Add current id to storage
console.log(id);
      }

 function setActive(value) {
document.getElementById(value).classList.value = "list-group-item active";
    }

Upon loading the page, it checks for the id in local storage and highlights the corresponding list item as active. The active function clears any previous data before adding the new id to local storage.

Answer №2

To assign an id to each a, utilize the Storage.setItem method:

localStorage.setItem(
  'activeListGroupItem',
  $('#collapse2 .list-group-item.active a').attr('id')
);

Then retrieve and reapply it using the Storage.getItem function:

$('#' + localStorage.getItem('activeListGroupItem'))
  .parent().addClass('active');

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

Struggling with grasping the concept of bootstrap scroll spy

I'm struggling to grasp the concept of scrollspy and how it functions. Despite reviewing numerous examples, I remain perplexed, which is why I've come here for help. My understanding is that scrollspy monitors scrolling behavior and triggers cert ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

Modifying the position of a component in the UI tree to reset its state in ReactJs

According to React, the state will be maintained as long as the same component is rendered at the same position. In this scenario, I have two Counter components rendering. By toggling a checkbox, I am able to control the visibility of the first Counter co ...

The foundation of JSON and its structural encoding

Looking to deserialize JSON from Java, here's how it's done: Java jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO); JSON "accounts" : [ { "name" : "1009427721", "value" : 16850.79, "children" : ...

Tips for customizing the appearance of grouped rows in a Vuetify datatable with the use of slots

Has anyone successfully utilized grouped rows with v-slot in the most recent Vuetify versions? The example they provide is as follows: <template> <v-data-table :headers="headers" :items="desserts" item-key="name" group-by="categ ...

Show a component when there is no input value, then conceal it when an input value is present

Recently, I attempted to position a paragraph absolutely in relation to an input element. My goal is to conceal the paragraph when the input has a value, and reveal it when the input is empty. Here is the code snippet I created, however, it doesn't ...

I am unable to append a new attribute to an object

I am currently working on a project using Node, Express, and Mongoose. In my controller, I'm trying to retrieve all orders for the logged-in client from the database. I want to display the status of each order and based on the state, add the available ...

Question about the origin of style sheet source files [*.css?ver=]

Can you explain the purpose of appending a query string to the end of a style sheet? I frequently come across examples like this: some-stylesheet.css?ver=1.2.3 Appreciate your insights. ...

Stop JQuery Timepicker from showing by using beforeShow event

I've been trying to figure out a solution for this issue, but so far I haven't been successful. When using the timepicker, there is a beforeShow property that I want to utilize for validation purposes. I need the timepicker to only appear if the ...

Display only the relevant search results using ng-show in AngularJS

By utilizing the code below, I am able to filter results where all entries are displayed on the page: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name: ...

Storing a string in a variable within Typescript

Attempting to read an XML file in Typescript using some JavaScript code, with the goal of adding the text content to a local variable. The code snippet is as follows: import { Injectable } from '@angular/core'; @Injectable() export class Jsonre ...

Vertical centering with stacked flexboxes is malfunctioning in Chrome

There is an issue with the following code snippet in Google Chrome: <div class="flex-container"> <div class="flex-item"> <div> <div> <h2>This is a test</h2> </div> </ ...

What are the steps to transition to the new Google Identity Service sign-in process?

I am facing a challenge in migrating my app to the latest Google identity service sign-in methods. I have been struggling with this for days and find Google's documentation quite confusing. That's why I'm reaching out here for some assistanc ...

What could be causing flexbox not to shrink to fit after wrapping its elements?

My goal is to create a flexbox with a maximum width that allows elements to wrap beyond that width without affecting the overall size of the flexbox's "row." The issue I am encountering is that when an element stretches beyond the maximum width and w ...

Struggling to access values from your model using EL in JavaScript? Let me provide some guidance

In my model, there is an object named "domain" with two methods: getDescriptionEn() and getDescriptionFr(). I am trying to retrieve the appropriate description based on the current locale. My issue lies in the following code snippet: var locale = "${cur ...

Leveraging async/await in conjunction with callback functions

I am in the process of creating a service layer on top of mongoDB. I have a User object that contains an array of referenced Achievements. Once the user is authenticated using JWT or another method, I go into the service layer and retrieve the relationshi ...

Employ ImageMagic in a synchronous manner

Consider utilizing imagemagick Required to use imagemagick in a synchronous manner. Meaning the following code should execute only after the image conversion is complete (regardless of any errors). The only solution I can see involves using deasync: co ...

Display the DIV element once a specific number of radio buttons have been selected

I need help figuring out how to display a DIV after a specific number of radio buttons are selected. Currently, I have it set up to appear only when all the radio buttons are selected thanks to some guidance from others who had similar questions. However, ...

Retrieve option elements from a select list based on their value(s)

I have the requirement to transfer specific <option> elements from one <select> list to another, and possibly back and forth. I cannot hard-code the data and need to identify the <option> elements I want to move based on their value attri ...

The functionality of new Date() is inconsistent when encountering a daylight savings time switch

In my current situation, I am facing an issue when passing "year, month, date, time" to the Date() function in order to retrieve the datetime type. Utilizing Google Chrome as the browser. The Windows system is set to the EST timezone (-05:00). Daylight S ...