Change div color with input type color and local storage

Hi FreeCodeCamp & All,

                                                         The below following is the full code where i am trying to learn the localstorage and the localstorage doesn't work.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>


.div1 {
  background-color: #ff0;width:150px;height:150px;
}
</style>
</head>
<body>

<h2>HTML Table</h2>

<input type="color" id="colorit" onchange="setColor()"/>
<div class="div1">
 
</div>

<script>

$(".div1").localStorage.getItem('bgcolor') ;
 var ClassName;

function setColor() {
  //localStorage.setItem('background', $('#colorit').val());
  ClassName = $('#colorit').val();
  $('.div1').css('background-color', ClassName);
   localStorage.setItem('bgcolor', 'ClassName');
}

function getColor() {
  //localStorage.getItem('background');
  $('#colorit').val(ClassName);
 localStorage.getItem('bgcolor') ;
}

setColor();

</script>
</body>
</html>

Could you able to solve it ?

Looking forward for a kind help and solution.

Cheers

Open up the browser console in dev tools and check out the error message you are getting.

Hi Bruce,

The error message is attached herewith.

I am unable to solve it out self.

Cheers

varghese

01-error.JPG

I’m assuming you’re trying to:

  • Control the color of the div1 class with the color picker
  • Persist that color in localStorage so that the div remains the chosen color on reload

To do that follow these steps

  • Add an event listener for the page load
    ** Get your color from local storage or a default color if you don’t have on
    ** set your div and picker to be the current color
  • make a method to handle the color pickers change
    ** get the current color value
    ** set your div1 class background color equal to that value
    ** store your value in local storage

If you try and are still stuck I made a code pen with an example. I didn’t use jquery. https://codepen.io/djpetifo/pen/zYZboVa?editors=1010

Overall your use of the localStorage api isn’t incorrect. The main issue is that you tried to call it as a method on your div. Also, it’s been years since I’ve used jquery but make sure you are correctly setting the styles on your elements. I’ve never used the .css property of an html element so I just used .style in my codepen

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.