It seems that sessionStorage and localStorage reset after refreshing the page

I have a local document for a project that doesn't run on a web server. It contains multiple pages, each with a sidebar that can be toggled open or closed. I have implemented sessionStorage to save the current state of the sidebar (open or closed), but I am facing an issue where the state resets to true upon refreshing the page.

The loadNav() function is linked to the body's onload property, which is responsible for initializing the sidebar state by checking the sessionStorage parameter. However, when inspecting the page using DevTools (F12), I notice that the value resets with each page refresh. This behavior is unexpected, and I am struggling to find a solution or workaround. I have even attempted using localSession, but encountered the same issue.

Referencing one of the pages' code snippet (only the content within the "main"

changes between pages), here is an example code. Please note that the sessionStorage functionality does not work in the StackOverflow sandbox:

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

/* Side Navbar */
function loadNav() {
    if(sessionStorage.getItem("sideNavOpen")) {
        openNav(false);
    } else {
        closeNav(false);
    }
}

function openNav(transition) {
    if(transition) {
        document.getElementById("sidenav").style.transition = "0.5s";
        document.getElementById("main").style.transition = "margin-left 0.5s";
    } else {
        document.getElementById("sidenav").style.transition = "none";
        document.getElementById("main").style.transition = "none";
    }
    document.getElementById("sidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    
    sessionStorage.setItem("sideNavOpen", true);
}

function closeNav(transition) {
    if(transition) {
        document.getElementById("sidenav").style.transition = "0.5s";
        document.getElementById("main").style.transition = "margin-left 0.5s";
    } else {
        document.getElementById("sidenav").style.transition = "none";
        document.getElementById("main").style.transition = "none";
    }
    document.getElementById("sidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";

    sessionStorage.setItem("sideNavOpen", false);
}
.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  padding-top: 60px;
}

/* Additional CSS styles omitted for brevity */

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Sprint0</title>
        <link rel="stylesheet" type="text/css" href="../styles/templateISS.css">
        <link rel="stylesheet" type="text/css" href="../styles/main.css">
        <link rel="stylesheet" type="text/css" href="../styles/sidenav.css">
        <link rel="stylesheet" type="text/css" href="../styles/topnav.css">
        <script type="text/javascript" src="../scripts/myScripts.js"></script>
    </head>

    <body onload="return loadNav();">
        <div id="openButton" class="openButton" onclick="openNav(true)">&#9776; Menu</div>
        <div id="sidenav" class="sidenav">
            <a class="closeButton" href="javascript:void(0)" onclick="closeNav(true)">&times;</a>
            <a href="../../index.html">Index</a>
            <a href="final_theme.html">Final Theme</a>
            <a href="requirement_analysis.html">Requirement<br/>Analysis</a>
            <a class="selected" href="problem_analysis.html">Problem Analysis</a>
            <a href="conclusions.html">Conclusions</a>
            <a href="team.html">Team</a>
        </div>

        <div id="main">
            <h1 align="center">Problem Analysis</h1>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </div>

    </body>

</html>

Answer №1

It is important to note that when using the getItem method in localStorage or sessionStorage, it is expected to return a string rather than a boolean value.

Therefore, it is necessary to implement the following verification in your code.

localStorage.getItem("loginStatus") === 'true'

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

Make sure to load the HTML content before requesting any input from the user through the prompt function

Could you please help me with a question? I'm looking to load HTML content before prompting the user for input using JavaScript's prompt() function. However, currently the HTML is only loaded after exiting the prompt. Below is the code that I hav ...

Having trouble finding the right path. Is there an issue with Angular routing?

After successfully creating a simple application, I decided to write test cases for it. My first attempt was to work on the routing part of the application. Check out the code on StackBlitz The routing code snippet is as follows: Main module: export cons ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...

Erase the white backdrop from the dragImage

Is there a way to remove the white outline that appears when dragging a draggable element from a dark background? I want to make it completely transparent. Here is a visual representation: https://i.sstatic.net/Eywf9.png Here is the code snippet: docume ...

Using VueJS to dynamically load a separate component into a Vue instance

Currently, I am working on revamping our web platform at my job. This includes migrating a significant amount of outdated JavaScript/jQuery code to VueJS. We have a "global.js" file that contains our Vue components and a "vendor.js" file that includes Vue ...

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...

Make a tab the active tab within the Material-UI tab component

For the current project, I have decided to utilize Material UI as the primary library. One of the pages in the project requires four tabs, which I am implementing using the tab component from the Material UI library. By default, when rendering the page wi ...

Are JSON-Web Tokens (JWTs) used for both verifying identity and granting access privileges?

Currently, I am exploring the process of developing a blog website that permits users to log in and perform tasks such as editing or deleting their own blogs based on their user role. If a different user logs in and does not own a particular blog, they s ...

Selecting HTML5 data attributes using jQuery

There is a button on my page with multiple data attributes, and I am trying to hide it by selecting it based on its class and two specific data attributes. <a href='#' class='wishlist-icon' data-wish-name='product' data-wi ...

Guide to incorporating eslint with Next.js in a project that already has an eslint configuration

I recently created a new next.js project within my existing Node.js project, which already has an eslint config set up. Here's how the folder structure looks now: ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

Setting the default time zone to UTC for Material UI date and time picker

Looking to implement a dialog in React with Material UI for users to input start and end date/time. The goal is to have the default start set to the beginning of the current day and the default end set to the end of the current day (UTC). However, I'm ...

Transform the JSON format received from the API endpoint to make it suitable for use in the component

I'm working on a react-native app that fetches event data from a wordpress endpoint. Below is the JSON I receive from the wordpress API. How can I restructure it to fit into my calendar component? Where should I handle this restructuring in my app? ...

What could be causing my problem with the add function?

I'm having trouble capturing the user input from modal input boxes and adding them to my state array. I've attempted to extract the values from the inputs and push them into a clone of the state array, then update the state with the clone. Howeve ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Retrieving images from GridFs and displaying them in an Angular application

I have been working on storing images from my angular app in MongoDB using GridFs. However, I am having trouble retrieving the images from the database to the app. I am using a custom objectId for the query. UPDATE After some changes, I managed to get t ...

Having trouble getting CSS absolute and relative positioning to work with my div slider carousel

I'm currently working on creating a slider carousel using VUE, where the CSS classes (3 divs) are looped through. However, I am facing an issue where every time a div fades out, the next slider creates a duplicate slider at the bottom, resulting in tw ...

methods for retrieving data from a Laravel controller within an imported JavaScript file

My current approach involves using ajax to update a table based on the user's input. $('#user').change(function(){ var user= $("#user").val(); if (user !='None'){ $.ajax({ type: "GET", url: '/getUserAccounts/&a ...

Uploading photos to Postgres through express/multer

Currently, I am using Postman to send images to a POST route through the Express library. However, when I retrieve the buffer of binary data, I am unable to process it accordingly. Will using body-parser resolve this issue? This is how I am uploading the ...

Reverting a concealed segment

Can anyone make sense of my unconventional explanation? I've set up a hidden section as shown below: <section class="intro"> <label> <input type="checkbox"> <span class="menu"> <span class="hamburger"></span&g ...