简体   繁体   中英

Change background colour of one div at a time using localStorage

I change the background color of a div to yellow after clicking on a button by using localStorage. If the user clicks on another button the old button still has a yellow background colour. It only turns white if I click on it again.

在此处输入图像描述

What I want to achieve is that only the button that was clicked on should have the yellow background colour, but I'm struggling to get this working using localStorage.

This is the function that changes the colour onclick:

function selected(item) {

    if(item.style.backgroundColor == 'yellow'){
        // means the item is selected already. So unset it.
        item.style.backgroundColor = 'white';
        localStorage.removeItem(item.id);
    }
    else{
        item.style.backgroundColor = 'yellow';

        console.log(item.id);
        localStorage.setItem(item.id, 'any value');
    }
}

This is what the divs look like:

<div class="link" id="firstlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Ulm" style="background-color: white;">Ulm</div> 

Here's the full code:

<style>

#sideNavBox {display:none}
#contentBox {margin-left:0px}
#nav {
  display: flex;
  flex-wrap: wrap;
  flex: 1 1 0px
}

.link {
  max-width: 150px;
  padding: 3px;
  margin: 10px;
  border: 2px solid lime;
  border-radius: 15px;
  flex-basis: 100%;
  text-align: center;
  cursor: pointer;
}

.active {
  background-color: lime
}

.dd13:hover { cursor: pointer; }

.dd13 {
color: #FFFFFF;
Font: 12px Arial
background-color:: #48A040;
Padding: 3px 3px 3px 3px;
}


#pageStatusBar{
    display:none!important;
}


</style><script>
window.addEventListener("load", function() {
  document.getElementById("nav").addEventListener("click", function(e) {
    if (e.target.classList.contains("link")) {
       location = e.target.getAttribute("data-link");
    }
  })
})

var divItems = document.getElementsByClassName("link");




function selected(item) {

    if(item.style.backgroundColor == 'yellow'){
        // unset the item that is already selected
        item.style.backgroundColor = 'white';
        localStorage.removeItem(item.id);
    }
    else{
        item.style.backgroundColor = 'yellow';

        console.log(item.id);
        localStorage.setItem(item.id, 'any value');
    }

}


</script> 
<h2>
   <b>Seminare nach Standort filtern</b></h2> 
<div id="nav"> 
   <div class="link" id="firstlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Ulm" style="background-color: white;">Ulm</div> 
   <div class="link" id="secondlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Taufkirchen" style="background-color: white;">Taufkirchen<br/></div> 
   <div class="link" id="thirdlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Oberkochen" style="background-color: white;">Oberkochen</div> 
   <div class="link" id="fourthlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Köln" style="background-color: white;">Köln</div> 
   <div class="link" id="fifthlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Friedrichshafen" style="background-color: white;">Friedrichshafen</div> 
   <div class="link" id="sixthlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Wetzlar" style="background-color: white;">Wetzlar</div> 
   <div class="link" id="seventhlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Kiel" style="background-color: white;">Kiel<br/></div> 
</div> 
<div id="register">
   <p>To register yourself to a seminar please click on this icon 
      <a title="Book for me" class="book-for-me-button"></a>. To register someone else to a seminar, please click on this icon 
      <a title="Book for me" class="book-for-user-button"></a>.<br/></p>
</div> 
<script>
    if(localStorage.getItem("firstlink")){
        document.getElementById('firstlink').style.backgroundColor = "yellow";
    }
    if(localStorage.getItem("secondlink")){
        document.getElementById('secondlink').style.backgroundColor = "yellow";
    }
    if(localStorage.getItem("thirdlink")){
        document.getElementById('thirdlink').style.backgroundColor = "yellow";
    }
    if(localStorage.getItem("fourthlink")){
        document.getElementById('fourthlink').style.backgroundColor = "yellow";
    }
    if(localStorage.getItem("fifthlink")){
        document.getElementById('fifthlink').style.backgroundColor = "yellow";
    }
    if(localStorage.getItem("sixthlink")){
        document.getElementById('sixthlink').style.backgroundColor = "yellow";
    }
    if(localStorage.getItem("seventhlink")){
        document.getElementById('seventhlink').style.backgroundColor = "yellow";
    }
</script>

I thought of doing something like this:

function selected(item) {
    if(item.style.backgroundColor == 'yellow'){
        // unset the item that is already selected
        item.style.backgroundColor = 'white';
        localStorage.removeItem(item.id);
    } else if((document.getElementById("firstlink") has backgroundcolour ) || (document.getElementById("secondlink") has backgroundcolour)... ){
       // remove backgroundColor
    } else{
        item.style.backgroundColor = 'yellow';
        console.log(item.id);
        localStorage.setItem(item.id, 'any value');
    }
}

but that's more or less pseudocode because I don't know how one can do that.

Any help is appreciated!

You could first make all links white before performing your yellow/not-yellow click logic.

Here's a working example (using fakeLocalStorage because SO doesn't allow localStorage):

 // change all but the locally stored link to white function allLinksToWhite() { let links = document.getElementsByClassName('link'); for (let link of links) { if (link.id === fakeLocalStorage.getItem(link.id)) { continue; } link.style.backgroundColor = 'white'; } } function selected(item) { allLinksToWhite(); if (item.style.backgroundColor == 'yellow') { item.style.backgroundColor = 'white'; fakeLocalStorage.removeItem(item.id); } else { item.style.backgroundColor = 'yellow'; // console.log(item.id); fakeLocalStorage.setItem(item.id, 'any value'); } } // a "fake" localStorage because SO blocks localStorage const fakeLocalStorage = { _storage: {}, getItem: (name) => fakeLocalStorage._storage[name], setItem: (name, value) => { fakeLocalStorage._storage[name] = value; }, removeItem: (name) => { if (fakeLocalStorage._storage[name]) { delete fakeLocalStorage._storage[name]; } } }
 .link { max-width: 150px; padding: 2px; margin: 4px; border: 2px solid lime; border-radius: 15px; flex-basis: 100%; text-align: center; cursor: pointer; }
 <div class="link" id="firstlink" onclick="selected(this)" style="background-color: white;">Ulm</div> <div class="link" id="secondlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Taufkirchen" style="background-color: white;">Taufkirchen<br/></div> <div class="link" id="thirdlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Oberkochen" style="background-color: white;">Oberkochen</div> <div class="link" id="fourthlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Köln" style="background-color: white;">Köln</div> <div class="link" id="fifthlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Friedrichshafen" style="background-color: white;">Friedrichshafen</div> <div class="link" id="sixthlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Wetzlar" style="background-color: white;">Wetzlar</div> <div class="link" id="seventhlink" onclick="selected(this)" data-link="/internalseminars/SitePages/InternalSeminars.aspx?locations=Kiel" style="background-color: white;">Kiel<br/></div>

Do you need to do it with localStorage? If you don't, you can just set a variable, let's say buttonThatIsCurrentlyYellow which stores the id of the button that is yellow at the moment. Then, when a new button is clicked, you change the button with id stored in that variable to white and make the new button yellow, updating the variable accordingly.

If you need to use localStorage, rather than setting multiple items, you could instead set just one, something like:

window.localStorage.setItem("yellowButton", "your-btn-id")

Then you always make buttons white by default except for the one with the id stored there. On each click you update "yellowButton" to reflect the id of the new button that should be yellow and update the colors accordingly (old id becomes white, new id becomes yellow)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM