Tips for preserving theme color selection using checkbox across page reloads

I have a checkbox that changes the theme between dark and light, with light being the default.

<div class="switch">
    <label>
        <input id="layoutSwitch" type="checkbox"><span class="lever"></span>
    </label>
</div>

Here is the jQuery code I am using:

$('#layoutSwitch').change(function() {
    if($(this).is(":checked")){
        $('#bodyLayout').addClass("bodyLayout"); 
        $('#leftMenu').addClass("leftMenu");
    }else{
        $('#bodyLayout').removeClass("bodyLayout");  
        $('#leftMenu').removeClass("leftMenu");  
    }
});

This is my dark theme CSS:

/* Dark Theme */
.bodyLayout {
    background-color: #525a69; }
       .leftMenu {
          background-color: #252d3a; }\

My goal is to keep the selected theme even after reloading the page, as well as maintain the state of the checkbox selection. However, when attempting to combine the following code with the above code, it doesn't work properly and selects all switches on the page instead of just the one selected.

$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});

Answer №1

Here is the solution you were looking for https://jsfiddle.net/jn1we569/6/

$('#layoutSwitch').change(function() {
  $('#bodyLayout').toggleClass("bodyLayout"); 
  $('#leftMenu').toggleClass("leftMenu");
  localStorage.setItem('layoutSwitch', $(this).is(':checked'));
});

localStorage.layoutSwitch === 'true'? $('#layoutSwitch').prop('checked', true).trigger("change"): '';
.bodyLayout {
  height: 100px;
  width: 100px;
  background-color: #525a69; 
}

.leftMenu {
  height: 100px;
  width: 100px;
  background-color: #252d3a; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switch">
    <label>
        <input id="layoutSwitch" type="checkbox"><span class="lever"></span>
    </label>
</div>

<div id="bodyLayout"></div>
<div id="leftMenu"></div>

This code may not work on stackoverflow due to localStorage, so please refer to the jsfiddle link provided.

To make it work, ensure you have the change event and properly set up your localStorage statement to track the checkbox status.

Instead of manually checking the checkbox status, utilize jQuery's toggleClass method for efficient toggling of classes.

Remember to encapsulate your JavaScript code within

$(document).ready(function(){...});
.

I hope this explanation helps you resolve your issue.

Answer №2

$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});

This block of code stores the input state in local storage.

An error exists in this code as it applies to all input tags on the page using $('input'). To specifically target the $('#layoutSwitch') checkbox, change $('input') to $('#layoutSwitch').

The corrected version is shown below:

$(function(){
    var test = localStorage.input === 'true'? true: false;
    $('#layoutSwitch').prop('checked', test || false);
    updateTheme();
});

$('#layoutSwitch').on('change', function() {
    localStorage.input = $(this).is(':checked');
    console.log($(this).is(':checked'));    // You can remove this line to avoid logging the value
    updateTheme();
});

function updateTheme()
    if($('#layoutSwitch').is(":checked")){
        $('#bodyLayout').addClass("bodyLayout"); 
        $('#leftMenu').addClass("leftMenu");
    }else{
        $('#bodyLayout').removeClass("bodyLayout");  
        $('#leftMenu').removeClass("leftMenu");  
    }
}

Answer №3

Modify the ID selector to include input1 and input2

    $(function(){

    for (var selectorId in localStorage){
       if(selectorId.contains("input")){
          var test = localStorage.getItem(selectorId) === 'true'? true: false;

          $('#'selectorId).prop('checked', test || false);
      }
    }


    $('input').on('change', function() {
        var selectorId = $(this).attr("id");
        localStorage[selectorId] = $(this).is(':checked');
        console.log($(this).is(':checked'));
    });


});

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

Vertical Alignment of Bootstrap Columns

Within the post section of my website, I have 4 columns with varying heights based on their contents using Bootstrap 4 grid system. As shown in the image below https://i.sstatic.net/ZHHqR.png When I resize the 4th column it rearranges. https://i.sstatic. ...

Tips on handling jQuery UI tabs fx: toggle option and using the activate function simultaneously during an event

Is it possible to simultaneously manage the "jQuery ui tabs fx: toggle option" and the "activate: function ()" at the same event? When attempting to use both the jQuery fx: toggle fade option and activate: function at the same click event, they seem to ma ...

Image cannot be inserted into the div container

I've created a wrapper div with a text div and an image div floating to the right. It should have been a simple task, but for some reason I can't seem to get it to work tonight. I'm completely stuck. Take a look at how it appears currently: ...

The AJAX function fires only on the first click and does not work upon subsequent clicks when utilizing buttons within dynamically created tables

Currently, I am facing an issue where I am attempting to trigger an event to delete an element. This particular delete event should apply to the element that is clicked as well as an object above it. The Ajax call below works perfectly fine when utilized w ...

Can you identify the distinctions between two almost identical HTML emails?

I am currently facing a puzzling situation. There are two emails that I have - one with a sidebar and one without. When the email with the sidebar is received in Gmail, it displays correctly. However, the email without a sidebar loses some formatting, incl ...

Real-time web page parsing in JAVA is dynamic and constantly evolving

My goal is to create a GUI application in Java that retrieves data from sports live score pages. I am new to this, so please excuse any basic questions. Essentially, I want to extract information from sites like: http://www.futbol24.com/Live/ http://liv ...

Can the title of href links be concealed?

<a href="link.html" title="Titletext"> ...is the code. I have a requirement to utilize the title attribute due to using slimbox, however, I am looking for a way to conceal the title text that appears when hovering over the link. Does anyone have a ...

What is the best way to store a range object obtained from getSelection in order to recreate it on a separate page load?

My goal is to develop a web application that enables users to highlight selected text on a webpage with the click of a button. I want these highlights to persist even when the user returns to the page. So far, I have achieved: var selectedRange = documen ...

Using a <button> tag instead of a <div> inside of a <button> is not allowed, as clickable divs are typically frowned upon. What

I'm currently developing a React App that functions as a calendar, allowing users to click on specific days displayed as large squares to view information for that day. For accessibility purposes, I initially considered using <button> elements b ...

Is it possible for Bootstrap 5 to extract data from an excel sheet and showcase it in an HTML table?

I have been scouring the depths of the internet with no success in finding a straightforward solution. I recently put together an HTML page that makes use of Bootstrap tables. Currently, my table contents are hardcoded directly into the HTML. I received a ...

Looking for a way to upload only part of a large file using HTML and PHP

Is it possible to create a PHP script that can upload only the first 1 MB of a very large file? Can this be achieved with a standard form upload in PHP by closing off the connection after 1 MB is uploaded? I have researched various uploaders (HTML5/Java ...

How can I display an image caption within a lightbox using jQuery?

There is a caption under each image. <p> <a href="large.jpg"> <img width="85" height="75" src="thumb.jpg/> </a>Caption</p> I am looking to display the same caption at the bottom of the lightbox. <span id="lightbox-image ...

What is the most effective method to ensure this layout is functioning properly?

Seeking a solution to an unexpected challenge, what initially appeared as a simple task has transformed into a complex dilemma. Balancing the vertical alignment of green DIVs while preventing absolute positioned elements from overlapping following content ...

A guide to transforming rows into columns with CSS

Hello, I am trying to convert rows into columns using CSS. Currently, my code looks like this: <style> .flex-container { max-width: 500px; width: 100%; display: flex; flex-wrap: wrap; } .flex-item { ...

In Safari, use a reversed angle for a -webkit-linear-gradient

While searching for a CSS solution to create a uniformly colored element with an angled start without using images, I came across a simple example that caught my attention: . This method works well in most browsers, but I encountered an issue in Safari whe ...

Struggling to customize the style of bootstrap components

Struggling to get my custom css to take precedence over Bootstrap4 components in my Django project. I'm a beginner in front-end development and I'm hoping to articulate my question clearly. Note: This is an HTML sheet within a Django project. My ...

Using a subheader in conjunction with a virtual repeater in markdown does not function correctly

Currently, I am utilizing angular 1 along with angular material. I am trying to incorporate md-subheader with multiple md-virtual-repeat-containers within an ng-repeat loop. The source code can be found on this codepen. The issue I am facing is slightly c ...

Accessing node modules in the index.html file located in the public directory

Is there a way to access node_modules, such as Angular, from my index.html file? This is the current file structure: node_modules public jsfolder cssfolder index.html server.js I am aware that this code snippet does not work in index.html: <scri ...

Spin picture and optimize margins

I need help rotating an image by 90 degrees that is positioned between two boxes. The issue I am facing is that the rotated picture overlaps with the two boxes in this scenario. Example 1: Incorrect formatting CSS: .box{ height:50px; width:200px ...

Create a stunning visual on the canvas using the high-resolution Retina display

Working on a web App in phonegap and trying to use a 320 by 480 image for drawing, but it appears fuzzy. html <canvas id="canvas" height=480 width=320> Your browser does not support the HTML5 canvas tag.</canvas> javascript var canvas = doc ...