Interested in retrieving the dynamically changing value of LocalStorage

Hopefully I can articulate my issue clearly.

I am implementing a feature where CSS themes change upon button clicks. When a specific theme button is clicked, the corresponding classname is saved to LocalStorage. However, since the key and value in LocalStorage are constantly changing, I would like to retrieve whatever is currently set in LocalStorage after the click event, rather than a hardcoded value. My code uses jQuery for handling button clicks, and below is the snippet. Any assistance would be highly appreciated.

$(document).ready(function(){

    $('#dark').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-dark');
        localStorage.clear();
        localStorage.setItem('theme-dark', ['theme-dark']);
        localStorage.getItem('theme-dark');
    });

    $('#light').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-light');
        localStorage.clear();
        localStorage.setItem('theme-light', ['theme-light']);
        localStorage.getItem('theme-dark');
    });

    $('#beaker').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-beaker');
        localStorage.clear();
        localStorage.setItem('theme-beaker', ['theme-beaker']);
        localStorage.getItem('theme-dark');
    });

    $('#outrun').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-outrun');
        localStorage.clear();
        localStorage.setItem('theme-outrun', ['theme-outrun']);
        localStorage.getItem('theme-dark');
    });

    var localItem = localStorage.getItem('theme-outrun');

    $('body').addClass(localItem);

});

Answer №1

Utilize a single key to designate various themes within the local storage

$(document).ready(function(){

    $('#dark').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-dark');
        localStorage.clear();
        localStorage.setItem('theme', ['theme-dark']);
        localStorage.getItem('theme');
    });

    $('#light').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-light');
        localStorage.clear();
        localStorage.setItem('theme', ['theme-light']);
        localStorage.getItem('theme');
    });

    $('#beaker').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-beaker');
        localStorage.clear();
        localStorage.setItem('theme', ['theme-beaker']);
        localStorage.getItem('theme');
    });

    $('#outrun').click(function(){
        $('#app-root').removeClass();
        $('#app-root').addClass('theme-outrun');
        localStorage.clear();
        localStorage.setItem('theme', ['theme-outrun']);
        localStorage.getItem('theme');
    });

    var localItem = localStorage.getItem('theme');

    $('body').addClass(localItem);

});

Answer №2

Utilize one key for both localstorage.setItem and getItem functions.

Alternatively,

As a final step, execute the following code:

var localItem  = localStorage.getItem(Object.keys(localStorage)[0])

$('body').addClass(localItem);

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 process for creating a custom hook in React.js/Next.js?

I encountered a problem while trying to create a hook from my code. Here is the snippet from the hook file: import { useRouter } from "next/router"; const useCurrentPath = () => { const { asPath, locale, defaultLocale } = use ...

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

Retrieve a string value in Next.JS without using quotation marks

Using .send rather than .json solved the problem, thank you I have an API in next.js and I need a response without Quote Marks. Currently, the response in the browser includes "value", but I only want value. This is my current endpoint: export ...

Transferring live data between AJAX-triggered pop-up windows

Utilizing modals frequently in my application is a common practice. There are instances where I need to transfer data from one modal box to another. For instance: Suppose there is a table listing different car manufacturers (Audi, BMW, Honda, etc). Each r ...

Using JavaScript, is there a way to modify a JSON parameter within an API?

My API provides JSON data structured like this: [{"NAME":"john","SURNAME":"johny","ADULT":"3","CHILD":"3","BABY":"0",}] In my JavaScript function, I need to send a request to a web service that will update the value of "BABY" from "0" to "1". Can this be ...

What is the most effective method for retrieving client-side generated controls and data in ASP.net?

I have successfully created a table of form fields using ASP.net and the repeater control, populated with data from a database. Now, I have enabled users to add new rows by using jQuery to dynamically add rows to the client-side HTML table (which is rende ...

There are no specified operations outlined in the Node.js Express documentation

swagger ui https://i.stack.imgur.com/UIavC.png I've been struggling to resolve this issue where the /swagger endpoint seems to only partially read the swagger.json file. Despite configuring everything correctly, no errors are appearing. It simply dis ...

What is the reason behind the observation of executed javascript upon receiving a JSON response from the server?

My current knowledge of HTTP involves web browsers sending mainly GET or POST requests, with the server responding accordingly. I am aware that servers can return a complete HTML document that is ready to be displayed in a web browser. Additionally, I un ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...

How can I adjust the size and width of the autofocus cursor inside an input box using Angular?

How can I modify the height and width of the cursor in an input field with auto focus? app.component.html <input class="subdisplay" [ngModel]="input | number" type="text" (keyup)="getValue(box.value)" name ...

Interval function failing to update information on Jade template

Currently, I am working on a Node app using Express and Jade. My aim is to retrieve JSON data from an API and have it refresh on the page periodically. To achieve this, I have created an empty div where I intend to inject the contents of a different route/ ...

When viewed on a mobile device, the page defaults to displaying the NumPad instead of the Text Keyboard in Angular

The email field in my angular app is opening a Key Pad in mobile view and I'm not sure why. <form (ngSubmit)="onSubmit()" #emailForm="ngForm"> <div class="emailaddress" style="text-align:center;" *ngIf="!showEmail"& ...

Trigger a function upon the addition of a class to a div element | Execute AnimatedNumber()

Is there a way to trigger a function when a specific div receives a certain class? I have an animated div that only appears when scrolling, and once it's visible, it gains the class "in-view". I want to execute a function every time this div has the ...

Using Javascript to apply styling only to the first class element in the document

I am facing a challenge with styling programmatically generated classes and inputs. Here is an example of the structure: <div class="inputHolder"> <input type="button" class="inputclss" value="1"> </ ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

Copy password input field content in Vue to clipboard

I'm currently working on a Vue app that includes a form input for creating passwords. I've managed to implement a button that shows/hides the password, but I'm struggling with adding a copy to clipboard function. It doesn't seem to be w ...

scrollable material ui chips list with navigation arrows

I'm attempting to create a unique scrollable chips array using Material UI version 4 (not version 5). Previous examples demonstrate similar functionality: View Demo Code I would like to update the scrolling bar of this component to include l ...

Why is it that styling <div> and <img> with a URL doesn't seem to work, even when applying the same styles?

In the example I have, I apply the same styling to an image and a div. Interestingly, the styling on the div makes the image look significantly better, while on the image itself it appears distorted. What could be causing this discrepancy? Both elements a ...

Understanding the res.render method in JavaScript can be a bit tricky at first

In my spare time, I have been immersing myself in coding lessons and have encountered some puzzling aspects of the code: Firstly, there is a confusion surrounding the action attribute in HTML Secondly, this particular piece of code is causing me some b ...