Tips for storing the state using Localstorage?

Greetings to the person reading this message!

I am relatively new to programming and I have a query... I created a Navigation bar: body > div > nav > div > ul > li*10

I have implemented the styling in CSS.

 //Navigation Bar
  const list = document.querySelectorAll('.list');

  function activeLink(){
    list.forEach((item)=>
    item.classList.remove('active'));
    this.classList.add('active');
  
  if(list.classlist.contains('active')){
    localStorage.setItem('on','true');
  } else{
   localStorage.setItem('on','false');
  }
  };
  
  if (localStorage.getItem('on') === 'true'){
    list.classList.add('active');
            
  } else {
    list.classList.remove('active');
    
  };


  list.forEach((item)=>
  item.addEventListener('click',activeLink));

The issue I'm facing is that the changes are not saved when I refresh the page or navigate to another section. How can I utilize localstorage for this purpose?

I have attempted different methods but haven't been successful yet.

Thank you in advance!

https://i.sstatic.net/pYncg.png

WATCH VIDEO WATCH VIDEO WATCH VIDEO WATCH VIDEO

Answer №1

It seems using localStorage may not be the best approach for accomplishing your goal. Instead, I recommend highlighting the link of each page when it is opened. This can be done by manually adding classes to each page's link, especially considering there are not a large number of links in the navigation.

Answer №2

It seems like the positioning of this code is a bit off.

if (localStorage.getItem('on') === 'true'){
  list.classList.add('active');
} else {
    list.classList.remove('active');
};

To ensure that the list has the correct class from the start, it should be executed immediately upon page load.

const list = document.querySelectorAll('.list');

This will guarantee the proper initialization of the list's class.

Answer №3

Uncertain about the purpose behind this section of the code, but the syntax being used appears to be correct. Here are some examples demonstrating how to utilize the local storage API:

To save a key-value pair to local storage, use the following syntax:

localStorage.setItem('key', 'value');

To retrieve the saved value, use this syntax:

localStorage.getItem('key');

If you encounter issues with the code functionality, try accessing your browser's developer tools to inspect the storage contents. If no entries are found in the local storage, the problem likely lies in saving the key-value pair.

Here is how you can access the developer tools in Chrome:

  • Press F12 on your keyboard (or Ctrl+Shift+J)
  • Follow the steps outlined in the provided image

https://i.sstatic.net/CzwvI.png

If the code still fails to work properly, review your browser settings to ensure that there are no security features obstructing your application from saving to local storage.

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 record and share a video with jquery and laravel?

Is there a way to grant users access to record videos within an application and then upload them after previewing? I've been able to successfully record and download a video, but now I'm unsure of how to proceed with uploading it to the server. ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

Display or Conceal Content Depending on the Button's Status

I am currently working on implementing an accordion style button for a project. I have configured my component to hide the list when the button is clicked, but I am encountering an issue where the list does not reappear. Additionally, I would like to inc ...

Concealed Selenium File Upload through Drag and Drop User Interface

Struggling to insert an image into the specified input using selenium web-driver. <input type="file" multiple="multiple" class="dz-hidden-input" accept="image/gif,image/jpg,image/jpeg,image/png,application/zip" style="visibility: hidden; position: abso ...

Concerns regarding rendering HTML and drawing in Node.js

Having an issue where node.js is serving an html file with an SVG drawing. The index.html features a chart similar to the line chart found at http://bl.ocks.org/mbostock/3883245 Whenever I try to serve the index.html through the express server, I end up ...

In JavaScript, combine two arrays of equal length to create a new array object value

Trying to figure out how to merge two arrays into a new object in JavaScript var array1 = ['apple', 'banana', 'orange']; var array2 = ['red', 'yellow', 'orange']; If array1[0] is 'apple&apos ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

How to retrieve documents in ElasticSearch based on field values containing or including specific values

I am attempting to retrieve documents from elastic search based on fields that include or contain dynamic text. For example: Here are some sample documents retrieved from elastic { id: 12345, name: test66, description: 'some desc231431', entity_i ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Guide to implement a confirmation box in PHP

I recently set up a Joomla article and integrated the Sourcerer Joomla extension to include JavaScript and PHP in my project. Currently, I am developing a course purchase site where users can buy courses from owners and credits are deducted upon every purc ...

Issues with Angular toggle sorting functionality not functioning as expected

$scope.searchObject = { from: 0, hydrate: false, size: 12, sort: 'timestamp:desc' }; $scope.sort = function(a) { var ascend = a + ':' + 'asc'; var descend = a + ':' + 'desc'; if ($scope.searc ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

The function Router.use() is in need of a middleware function, but instead received an undefined

A snippet of code from my index.js file looks like this: ... import userRoutes from './src/routes/userRoutes'; import invoicesRoutes from './src/routes/invoicesRoutes'; import authMiddleware from "./src/middlewares/authMiddleware"; ... ...

Dealing with the hAxis number/string dilemma in Google Charts (Working with Jquery ajax JSON data)

My Objective I am attempting to display data from a MySQL database in a "ComboChart" using Google Charts. To achieve this, I followed a tutorial, made some modifications, and ended up with the code provided at the bottom of this post. Current Behavior T ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

Updating the route in Express.js/Node.js to redirect form submission from `/page` to `/page/<input>`.Is this fine for you

How can I redirect a user from /page to /page/:nickname in Express after they enter a nickname and click submit? This is my code: // app.js app.get("/page", (request, response) => { response.render("page"); }); app.get("/page/:nickname", (reques ...

How can I center the navbar logo and use it as a toggle for collapsing the menu?

This is a simple example of a navigation bar <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class ...