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

Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure: { "/home":{ "token":"ksdjfglkas" }, "/logout":{ "token":"ksdjfglksaudhf" } } It is necessary to access the token within the routes function. The JavaScript code ...

proper integration of socket.io

I have been experimenting with socket io for my project to display online friends, and I have noticed an issue that seems strange to me. Every time the page is rerendered (whether due to a user changing their profile information or sending a friend request ...

Implementing JavaScript Functions to Trigger Control Key and Plus/Minus Events

In my project, I have a unique set of selectors called A+. By clicking on the A+ button, it has been programmed to initiate the control plus event. Similarly, within the same interface, I also have an A- button that activates the control minus event when ...

I customized the navbar in Bootstrap by centering it with custom CSS, but whenever I click on it, it suddenly shifts to one side. I'm puzzled as to why this is happening and

I attempted to center my navbar-toggler element, but was only successful in centering the navbar-contend using Bootstrap. I then took it a step further by trying to center the navbar-toggler icon with custom CSS, however, it now shifts to the left when cli ...

Extracting URLs using Selenium from specific cells within a table

While parsing a webpage table, I noticed that one of the columns contains a hyperlink. The structure of the table is as follows: <table id="GridView1"> <tbody> <tr> ... </tr> <tr> ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

adaptive height that scales with content proportionally

I am looking to achieve a responsive height based on the content inside my container. For example, I want the height of the container to adjust according to the text it contains. <!DOCTYPE html> <html lang="en"> <head> < ...

Why is React JS unable to discover my exported modules?

Upon running my React app, the console displayed the following error message: Failed to compile. ./src/components/login/index.js Attempted import error: 'Login' is not exported from './login'. Here is an overview of the folder struct ...

Allow the button to be clicked only when both options from the 1/3 + 1/3 radio buttons are selected

How can I ensure that the next <button> at the bottom of the HTML is only clickable when at least one of each <input type="radio"> is checked? Also, how do I integrate this with my current function? The button itself triggers a jQuery function ...

React checkbox displaying incorrect render

I'm currently working on developing a React component that acts as a tile representation. This particular component consists of a div containing a label and a checkbox. The issue I'm facing is that I can click anywhere on the component to trigg ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

What is the process for updating a collection in MongoDB database with PHP?

After writing a code snippet to gather user input through a form and update a collection based on the entered product ID, I am encountering issues with incorrect results. It seems that I am unable to fetch the correct product ID value, which is causing t ...

Is it achievable to create shadows that do not overlap?

When you hover your mouse over the pill-shaped object, it should smoothly move over the circle as desired. However, the shadow of the circle still remains visible creating an unwanted effect. I am looking for a solution where the shadows do not overlap but ...

how to share global variables across all components in react js

Operating a shopping cart website requires transmitting values to all components. For instance, when a user logs into the site, I save their information in localStorage. Now, most components need access to this data. My dilemma is whether I should retriev ...

jQuery tooltips experiencing lag or duplication when closing on adjacent elements

My tool tips are not disappearing correctly, specifically in IE where they lag after you move to the next element. Using jQuery: $(document).ready(function() { loadMap(x, y,z); $(document).tooltip({ at: 'center top', my: ...

Efficiently formatting text in a div container

How can I ensure that the text within a span is word-wrapped inside a div? https://i.sstatic.net/W691d.png Here is the code snippet: <div class="col-xs-6 choice btn btn-default" > <span class="pull-left">(Kepala) Bagian Purchasing (not lis ...

What is the best way to integrate a loop in JavaScript to retrieve values?

<script> var data={ Data: { name: 'aaaa', number: '0003' }, values: { val: '-20.00', rate: '22047' }, user: [ '6|1|5', '10|1|15' ] }; ...

Using jQuery and JSON data to dynamically populate a second dropdown menu with filtered options

I am working on a form with two drop-down menus and a text box. The first drop-down contains static values, while the second drop-down is populated dynamically from a JSON array. My goal is to filter the options in the second drop-down based on the selecti ...

Error: Module not found - Imported Node Module

I have been struggling to make modifications to an npm package with little success. I have spent hours troubleshooting and would greatly appreciate some guidance. https://www.npmjs.com/package/dxf After forking the package into my Github account, I proce ...

Show the profile picture of a model in a Django template

I am trying to display the user's image by inserting it into the src attribute of the img tag, but I am facing difficulties with it. Here is my code: models.py class allusers(models.Model): user = models.OneToOneField(User, on_delete=models.CASC ...