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

The tip display script is unable to revert back to its original content

I managed to show a block of text in a td after a mouseover event, but I want to revert back to the original content on mouseout/mouseleave. The code I used is below. Please help. I am getting an undefined error when running the code. I suspect the issue l ...

Style your content using PHP and CSS to format text with multiple selectors

My HTML code looks like this: <div id="main"> <aside class="readableCenterAside left"> ## Content 1 ## </aside> <aside class="readableCenterAside right"> ## Content 2 ## </aside> </div> Here is my CSS: .readableCe ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

Issue: Module 'ansi-styles' not found when using AngularJS and Yeoman generator

Previously my code was functioning perfectly, but now it seems to have suddenly stopped working. Attempting yo angular:route api resulted in the following error message: Error: Cannot find module 'ansi-styles' at Function.Module._resolveFilen ...

What steps can I take to guarantee that my grid always accommodates its child without being too small?

My current setup involves utilizing a grid layout to arrange elements in the z-direction. However, I have encountered an issue where a child element extends beyond the boundaries of the grid element: #z-stack { display: grid; border: 5px solid ...

How to Use AJAX to Read a Text File in JavaScript

Having trouble with AJAX! I have successfully set up a marquee on my website, but now I want it to dynamically fetch the text from a text file. The goal is to read the text from the file (which contains only one line) and assign it to a global variable nam ...

Is there a way to animate without specifying a duration?

Exploring the capabilities of the Animated component in react-native, I came across the powerful Animated.timing(); function which operates within a specific duration defined as duration: 2000,. While duration is useful in certain scenarios, I found myself ...

Tips for uploading a file with fetch

While I know this question has been asked before, none of the solutions seem to be working for me. Initially, I attempted to resolve the issue using axios, but it appears that there is a bug preventing me from utilizing it for file uploads. Therefore, I am ...

Is there a way to regularly extract the most up-to-date HTML code from a dynamic website for designers to work

Our team of designers is responsible for creating graphical mockups, initial html, css, and image sprites for new designs. They also maintain these files. Once the hand-off is complete, our developers then take everything and work it into .Net code, templa ...

Unexpected behavior exhibited by DOM elements

I can't seem to figure out this issue. Every time I run this loop: for ( var i=0; i < 10; i++ ) { var $items = $(balls()); console.log($items); $container.imagesLoaded(function(){ $container.append( $items ).masonry( 'app ...

Resizeable drag and drop two-column design

Experimenting with creating a drag re-sizable layout using jQuery UI was quite an interesting challenge for me. If you want to check out the result, here is the link. However, my original goal was to achieve something different from what I ended up with. ...

What steps do I need to take to successfully integrate Font Awesome 5 with React?

Here is an interesting scenario: the initial icon is displayed, but it fails to update when the class changes. const Circle = ({ filled, onClick }) => { const className = filled ? 'fas fa-circle' : 'far fa-circle'; return ( ...

How can jQuery be prompted to execute a query at regular intervals every X hours?

I'm facing some issues with events in PHPMyAdmin as I do not have super user permissions. Despite contacting my host for help, they have not been cooperative. As a solution, I am considering running a specific PHP query every hour. Is this feasible? ...

bespoke JavaScript confirmation dialogue box

After customizing a confirmation box for the logout feature, I encountered an issue. When the user presses cancel, the box closes and control remains on the same page as expected. However, when the user clicks yes to logout, nothing happens. Could anyone p ...

Conduct a unit test to verify that a function successfully connects to an API and accurately stores the retrieved data in a variable

Currently, I am working on creating a unit test for my writing and JavaScript code. This area is still challenging for me, so I am in the process of learning how to do it correctly. The specific function I am focusing on makes an API call and then assigns ...

The occurrence of an error is triggered by the Jquery.ajax()

Here's a useful link for you to try out: If you take a closer look, you'll see that it takes the $_GET['fname'] parameter and outputs the content I need. I made an attempt at solving this: $.ajax({ type: 'GET', url: ...

Is it considered acceptable to include a JSONP request within another JSONP request?

Can you confirm if the code below is valid? $.getJSON(server_url+"?callback=?",{id:deleteId,pw:password,action:"editpassword"},function(data){ $.getJSON(server_url+"?callback=?", {id:deleteId,pw:password,action:"editpassword"},function( ...

The React functional component captures a snapshot of its state when initializing a websocket event handler

When using a react functional component, it captures a snapshot of the state at the time of subscription. For example, refer to the code below. If I click the setSocketHandler button and then press the setWelcomeString button. If I receive a message over ...

Exceptionally high memory usage detected in AngularJS

My AngularJS application is running into performance issues due to high memory consumption. There are around 200-250 repeated elements, each containing inner items with nested ng-repeats. The JS Heap memory allocation reaches up to 70MB, causing the webpag ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...