Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page.

To implement this, I inserted a color picker in my HTML:

<input type="color" id="colorID" oninput="changeColor()">

I then found this code online:

// When input changes, store value as 'storedValue'
function changeColor() {
  var userColor = document.getElementById('colorID').value;
  localStorage.setItem('storedValue', document.body.style.backgroundColor = userColor);
}

// If there is a stored value, update color picker and background color
if(localStorage.storedValue) {
  document.getElementById('colorID').value = localStorage.storedValue;
  document.body.style.backgroundColor = localStorage.storedValue;
}

My aim was to replace "document.body.style.backgroundColor" with my --main-color: #fff; from :root. Despite trying various alternatives like using document.documentElement, nothing seemed to do the trick!

Answer №1

Check out this solution:

// Creating a function that runs immediately after the page loads
(function(){
if(localStorage.getItem("storedValue")){
  document.getElementById('colorID').value = localStorage.storedValue;
  document.querySelector(':root').style.setProperty('--main-color', userColor) = localStorage.storedValue;
})();

// This function changes the color based on user input and saves it
function changeColor() {
      var userColor = document.getElementById('colorID').value;
      localStorage.setItem('storedValue', document.querySelector(':root').style.setProperty('--main-color', userColor));
    }
    
    // If there is a stored value, update color picker and background color accordingly
    if(localStorage.storedValue) {
      document.getElementById('colorID').value = localStorage.storedValue;
      document.querySelector(':root').style.setProperty('--main-color', userColor) = localStorage.storedValue;
    }

Answer №2

Trying to retrieve a value from local storage using this code is incorrect:

function changeColor() {
      var userColor = document.getElementById('colorID').value;
localStorage.setItem('storedValue', document.body.style.backgroundColor = userColor);
}
    
    if(localStorage.storedValue) {
        document.getElementById('colorID').value = localStorage.storedValue;
        document.body.style.backgroundColor      = localStorage.storedValue;
    }

The correct way to access stored values in local storage is as follows:

 function changeColor() {
          var userColor = document.getElementById('colorID').value;
          document.body.style.backgroundColor=userColor;
          localStorage.setItem('storedValue', userColor);
        }
    
        if(localStorage.getItem("storedValue")) {
             let storedValue=localStorage.getItem("storedValue");
             document.getElementById('colorID').value = storedValue;
             document.body.style.backgroundColor      = storedValue;
            }

Answer №3

A key aspect to keep in mind is that writing/reading data in the local/session storage requires the use of stringify/parse methods:

// Embed a hidden input in your HTML file
<input type="hidden" value="your_css_variable_value" id="myId"/>

// Access the element in your JS file and retrieve its value
const bgColor = document.querySelector('#myId').value;

// When there's an input, capture it as 'storedValue'
function changeColor() {
  var userColor = document.getElementById('colorID').value;
  document.body.style.backgroundColor      = userColor;
  localStorage.setItem('storedValue', JSON.stringify(userColor));
}

// If there's a stored value, update the color picker and background color accordingly
if (localStorage.getItem('storedValue')) {
  const savedColor = JSON.parse(localStorage.getItem('storedValue'));
  document.getElementById('colorID').value = savedColor;
  document.body.style.backgroundColor      = savedColor;
}

Answer №4

Just wanted to give an update on this thread and express my gratitude for all the responses.

In my initial question, I provided an example that confused some individuals. Here is the actual task at hand:

// Capture input value and store it as 'storedValue'
function changeColor() {
  var userColor = document.getElementById('colorID').value;
  localStorage.setItem('storedValue', document.querySelector(':root').style.setProperty('--main-color', userColor));
}

// If a value is stored, update color picker and background color
if(localStorage.storedValue) {
  document.getElementById('colorID').value = localStorage.storedValue;
  document.querySelector(':root').style.setProperty('--main-color', userColor) = localStorage.storedValue;
}

The current issue I'm facing is that the data doesn't persist when I refresh the page. I feel like I'm so close to getting it right! What adjustments should I make to get this code functioning properly?

Answer №5

Give this a shot:

inputColor.addEventListener("input", changeColor, false);

function changeColor() {
    debugger;
  var userColor = document.getElementById('colorID').value;
  localStorage.setItem('storedValue', JSON.stringify(userColor));

    // check if there is a stored value and update color picker and background color
if (localStorage.getItem('storedValue')) {
  const savedColor = JSON.parse(localStorage.getItem('storedValue'));
  document.body.style.backgroundColor      = savedColor;
}
    
}

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

I have noticed that the share buttons on Sharethis.com only show up after I resize the viewport

After integrating share buttons from Sharethis.com, I noticed that they do not appear when the page is refreshed. However, when I resize the viewport, they suddenly show up. <!DOCTYPE html> <html lang="en"> <head> <script t ...

What is the process for modifying a Joomla plugin?

Just starting out with Joomla development and recently installed Joomla 2.5 on my local computer for some practice. I have a question about editing Joomla plugins - specifically the layout of the Content - Pagebreak plugin (the pagination that appears wh ...

Link functioning properly for one item but failing for another

I am facing an issue with my index.html file that contains the following code: <li> <a href="imprint.html#imprint-link"> <div class="main-menu-title">IMPRINT</div> </a> </li> Clicking on the "IMPRINT" link loa ...

Tips for achieving seamless scrolling with the combination of javascript and css

Looking for a solution to achieve smooth scrolling on an HTML page without using the #id_name to scroll to a specific div. Instead, I want to scroll to a particular point, such as having a button that scrolls down the webpage smoothly by 250px when press ...

Confusion arises from conflicting Vue component script indentation guidelines

As I work on setting ESLint rules for my new Vue project, I am extending both eslint-plugin-vue and airbnb. All is well except for one issue - the indentation of the tag inside Vue components. The usual accepted format looks like this: <script> ex ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Is it possible to stream audio using a web socket?

I'm currently working on an app that streams audio from a microphone using web sockets. I'm struggling to play the web socket response in an audio control. Can someone please provide guidance on how to play audio buffer in an audio control? Your ...

Refresh the view seamlessly using Ajax without reloading the page

When a button is clicked, the following code will run: $.ajax({ type: "POST", url: base_url+"/controller/method", data: {val: value}, success: function(data){ data = jQuery.parseJSON(dat ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...

Mocha maintains the integrity of files during testing

After running a unit test to update a config file, I noticed that the file was altered. My initial thought was to use "before" to cache the file and then restore it with "after". mod = require('../modtotest'); describe('Device Configuratio ...

The Ajax request is not passing the values of the submit button as expected

In my current setup, I am using ajax code to send name/email/message parameters to a "messageaction.cfm" template and then display those same 3 parameters on the original submission page. The code works fine in achieving this functionality: <script ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

integrating a ui-bootstrap modal in a sidebar using angularjs

I recently utilized the modal example from https://angular-ui.github.io/bootstrap/ and everything worked perfectly. By using the code snippet below, I was able to successfully open the modal as shown in the example: $scope.open = function (size) { v ...

Create a division that will remain visible on the screen and allow scrolling when a certain class is

Having some trouble with a fixed class div that is not continuing to scroll after the class is removed on scroll. I've attempted to fix this issue but the div keeps getting hidden instead of continuing to scroll. If anyone has any advice or can poin ...

Enhancing the appearance of multiple images with CSS and Bootstrap styling

I am struggling to arrange multiple images in my booking system as they are all displaying in a single column rather than the desired layout What I had hoped for was a layout like this Currently, I am using bootstrap to format the images. My goal is to i ...

Adding middleware to the res.render() function can be extremely helpful when dealing with a large number

Recently, I put together a webpage for local use and it involves many routes. Specifically, I have 31 .ejs files and 3 .html files all neatly stored in the "views" folder. //app.js - using node and express app.get('/page1', function(req, res ...

Erasing a comment creates empty spaces

I've encountered an issue with my idea whiteboard where removing comments leaves unwanted blank spaces between ideas. For example, if I have the following comments: But when I delete something: Is there a way to ensure that no gaps are left between ...

Why isn't my Vue.js application automatically refreshing when I add or remove an object from the array?

In my Quasar and Vue.js project, I am working on a form where I can add objects to an array for insertion into the database simultaneously. However, I am facing an issue where the additions or deletions in the array only reflect on the screen after focusin ...

How to make a routerLink clickable within an anchor tag in Angular 6

I am facing a peculiar issue with a group of hyperlinks. html <div class="col-12 navlinks"> <div class="text-center"> <div class="justify-content-center"> <a class="col-auto d-inline-block whitelink" rou ...