Tuesday, 25 December 2018

How to set body background color before in javascript?

I'm using this script to allow user to change the background color...

    document.onclick = function SetFavColor(e) {
    if (e.target.className == 'AvcGbtn') {
        var favColor = e.target.style.backgroundColor;
        localStorage.setItem('color', favColor);
        document.body.style.backgroundColor = favColor;
        console.log(favColor);
    }
};

document.addEventListener('DOMContentLoaded', function GetFavColor() {
    var favColor = document.body.style.backgroundColor;
    var color = localStorage.getItem('color');
    if (color === '') {
        document.body.style.backgroundColor = favColor;
    } else {
      document.body.style.backgroundColor = color;
    }
});

CSS

body {
  max-width: 100%;
  min-width: 100%;
  height: 100%;
  font-family: normal;
  font-style: normal;
  font-weight: normal;
  background-color: transparent;
}


.AvcGbtn {
  display: inline-block;
  width: 2em;
  height: 2em;
}

HTML

    <span class="AvcGbtn" style="background: #ffffff; background-size: 100% 100%;" rel="nofollow"></span>      

    <span class="AvcGbtn" style="background: #757575; background-size: 100% 100%;" rel="nofollow"></span> 

This is working, but the problem is that it shows the selected color after page is fully loaded. I want to show the color the user selects before the page is loaded.

Example: background color is white, and user selects red. The script shows a white background color before selection, and after the user selects red, the script changes the background color to red. How can I do this?



from How to set body background color before in javascript?

No comments:

Post a Comment