Div input type color with localstorage

1 Answer 11 Views
Forum suggestions Miscellaneous
varghese
Top achievements
Rank 1
varghese asked on 17 Jun 2021, 04:27 AM
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.

Cheers

varghese

1 Answer, 1 is accepted

Sort by
0
Doncho
Telerik team
answered on 21 Jun 2021, 10:57 AM

Hi Varghese,

I have copied the provided code to a standalone Html page to test it and I have noticed a JavaScipt error on the console: 

Please note that the localStorage is a property of the Window. The $("div1") is not exposing such a property hence $("div1").localStorage is undefined, check out Troubleshooting JavaScript errors.

I am also not sure if I understand the desired behavior based on the provided code. If you share what is the expected behavior we could try to assist in achieving it?

Additionally, I have noticed that in the SetColor() function the string "ClassName" is set as a value of the localStorage item instead of the variable ClassName. This would result in localStorage pair bgcolor: "ClassName" instead of bgcolor: "#ffffff" for instance.

Since this issue is generic and not directly related to Telerik I would suggest you research some resources about the usage of localStorage. Here are a couple of articles to start with:

I hope you will find this information helpful.

Kind regards,
Doncho
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
Forum suggestions Miscellaneous
Asked by
varghese
Top achievements
Rank 1
Answers by
Doncho
Telerik team
Share this question
or