Em Sta
Em Sta

Reputation: 1706

Change background color with local.Storage (value)

I want to change the background-color of an div:

Arrow Box

For this i have to divs wich you can click. The triggerd function saves the local storage value of the "farbe" key.

<div class="radior" style="background-color:#8066CC;"    onClick='localStorage.setItem("farbe","#8066CC");hey()'></div> 

So after that, the value of the key "farbe" is asked. Besides this is makes an case ... I think you better read my code, because think i need some englisch lessons sorry!

function hey(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black"

case "#1bc38e":
var h = "turk"

case "#C3594B":
var h = "red"

case "#8066CC":
var h = "lila"
    }
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=""+h+""; ;

   }

SOmehow it doesnt function! Or you watch an example of my problem at fiddle http://jsfiddle.net/PpsLH/4/ ! Greetings from Germany!

Upvotes: 1

Views: 1925

Answers (3)

Sir Lojik
Sir Lojik

Reputation: 1429

try this

<div  class="arrow_box"><a>Arrow Box</a></div>


<div class="radior" style="background-color:#C3594B;" onClick="localStorage.setItem('farbe','#C3594B');window.hey()"></div>
<br>
<div class="radior" style="background-color:#8066CC;" onclick='localStorage.setItem("farbe","#8066CC");window.hey()'></div>

and for javascript

window.hey = function ()
{
    var h="";
    if (localStorage.getItem("farbe")=="#121212")
    {
        var h = "black";
    } else
    if (localStorage.getItem("farbe")=="#1bc38e")
    {
        var h = "turk";
    } else
    if (localStorage.getItem("farbe")=="#C3594B")
    {
        var h = "red";
    } else
    if (localStorage.getItem("farbe")=="#8066CC")
    {
        var h = "lila";
    }
    document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h+"";
}

Upvotes: 1

Chris Danek
Chris Danek

Reputation: 687

You should remove any inline event handlers from your code. Also the whole switch section and changing to named CSS colors seem redundant. Check out this bit of code written in jQuery

var box = $('div.arrow_box');

$('body').on('click','div.radior',function(e){
    var color = $(e.target).css('backgroundColor');    
    localStorage.setItem('farbe',color);
    box.css('backgroundColor',color);
});

and a working fiddle http://jsfiddle.net/chrisdanek/BaJvC/5/

Upvotes: 1

Tarandeep Gill
Tarandeep Gill

Reputation: 1536

Change your function to:

hey = function(){
  switch (localStorage.getItem("farbe")){
    case "#121212":
    var h = "black";
    break ;

    case "#1bc38e":
    var h = "turk";
    break ;

    case "#C3594B":
    var h = "red";
    break ;

    case "#8066CC":
    var h = "lila";
    break ;
  }
    document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h;
}

By the way, lila is not a valid HTML color, so it will not work.

Upvotes: 1

Related Questions