Search code examples
javascripthtmlarrayslocal-storagepopover

How do I use stored color values in local storage?


My problem is that I don't know why the background-colors picked for the buttons (red, green or blue) don't get saved in the local storage. What I want is to save the background-color locally in the browser, so the background-color will stay the same, even if the website is refreshed.

The value of the color is now just saved in the local storage like a string.

I have tried many different ways to deal with this but have not come up with a workable solution. If you can see anything wrong with the code or the structure, it would be very appreciated if you could share some code or tips!

Run the code from codepen: https://codepen.io/krantza/pen/KKpJmZm

// On click on a button, a popover menu will show up
$("[data-toggle=popover]").popover({
  html: true,
  sanitize: false,
  trigger: 'focus',
  content: function() {
    return $('#popover-content').html();
  }
});
// Creates data items inside local storage to save the name of the color that is picked
var saveColorPref = (i, c) => {
  localStorage.setItem("color-" + i, c);
  return c;
}
// Retrieves data items from local storage
var getColorPref = (i) => {
  return localStorage.getItem("color-" + i) || "";
}
// Load all the preferences
var loadColorPrefs = () => {
  $(".myBtn").each(() => {
    var i = $(this).index();
    $(this).css("background", getColorPref(i));
  });
}
loadColorPrefs();
// Set the color on click
var targetBtn;

function setColor(c) {
  var i = $(targetBtn).index();
  console.log(i, c);
  $(targetBtn).css("background", saveColorPref(i, c));
}
$('.myBtn').each((i, item) => {
  $(item).click((e) => {
    targetBtn = e.target;
  });
});
// Get the items from localStorage and apply the style
document.querySelectorAll('.myBtn').forEach((item) => {
  const id = $(item).attr("id")
  $(item).css("background-color", localStorage.getItem(id));

  item.addEventListener('click', (e) => {
    targetBtn = e.target;
  })
})
.popover-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  width: 200px;
  height: 60px;
}
.close {
  float: right;
  position: absolute;
  top: 0px;
  left: 183px;
}
.demo1 {
  background-color: red;
}
.demo2 {
  background-color: green;
}
.demo3 {
  background-color: blue;
}
.hide {
  display: none;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>


<button class="myBtn" data-toggle="popover" data-placement="bottom" data-html="true">1</button>
<button class="myBtn" data-toggle="popover" data-placement="bottom" data-html="true">2</button>
<div id="popover-content" class="hide">
  <button class="demo1" onClick="setColor('red')">Red</button>
  <button class="demo2" onClick="setColor('green')">Green</button>
  <button class="demo3" onClick="setColor('blue')">Blue</button>
  <span class="close">&times;</span>
</div>

or look the code at the code-snippet:


Solution

  • There are 2 different parts of the code that try to apply the saved colors.

    This one can't works because there's no id attribute in your myBtn buttons:

    // Get the items from localStorage and apply the style
    document.querySelectorAll('.myBtn').forEach((item) => {
      const id = $(item).attr("id")
      $(item).css("background-color", localStorage.getItem(id));
    
      item.addEventListener('click', (e) => {
        targetBtn = e.target;
      })
    })
    

    And this one:

    // Load all the preferences
    var loadColorPrefs = () => {
      $(".myBtn").each(() => {
        var i = $(this).index();
        $(this).css("background", getColorPref(i));
      });
    }
    loadColorPrefs();
    

    On codepen, this refers to the window object. Use the build-in element of jQuery each

    Function( Integer index, Element element )

    var loadColorPrefs = () => {
      $(".myBtn").each((i, e) => {
        $(e).css("background", getColorPref($(e).index()));
      });
    }
    loadColorPrefs();