Home > Net >  Check if a item in LocalStorage is null and isint changing backgrounds
Check if a item in LocalStorage is null and isint changing backgrounds

Time:11-21

I made a page of configurations that when i press a button it changes the background, to a color or to a image, i created the localStorages img,and color, my problem is that when they arent null at the same time, instead of the background going for image it goes for making the background with the "color", the code i am trying is this:

  if (localStorage.getItem("Color") === null) { //if Color is null
    if (localStorage.getItem("img") === null) {// And Image too
      document.body.style.backgroundImage = "url('css/Images/Instruments/pexels-pixabay-459797.jpg')"; // a image appear in the background
    } else { // else if Color is null but img isint
      document.body.style.backgroundImage = localStorage.getItem("img"); //load the image in the background
    }
// THIS IS My problem: i dont know how to check if both arent null
    if(localStorage.getItem("Color") !== 'null' localStorage.getItem("img") !== 'null'){ //If Both arent null
      document.body.style.backgroundImage = localStorage.getItem("img"); // load the Image not the background
    }
  }};

CodePudding user response:

Just had to remove the other local-storage item by using "localStorage.removeItem('item')" (Still Testing)

CodePudding user response:

you can use the logical operator &&, like this:

if (!localStorage.getItem('color') {
  if (!localStorage.getItem('img') {
    document.body.style.backgroundImage = 'url("your image url")';
  } else {
    document.body.style.backgroundImage = localStorage.getItem('img');
  }
  if (localStorage.getItem('color') && localStorage.getItem('img') {
    document.body.style.backgroundImage = localStorage.getItem('img');
  }
}
  • Related