codeWithMe
codeWithMe

Reputation: 892

Change the background of my webpage with local storage

For a very long time I have been wondering how to change my background-image on a webpage I code, but when the user refreshes my website I want their changes to still be there. Like they change the background with a click, and when they refreshes the page I want that background to still be there for them. Do I have to use local storage or cookies? In that case can someone teach me how?

Thank you for taking your time to read this and I hope I get a good answer.

An example of my code: http://koda.nu/arkivet/33733671 (password: "cwm", open in fullscreen). And I do have tried to learn localStorage.

Upvotes: 1

Views: 101

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206151

var body = document.body;

// Apply if present in storage
if (localStorage.bgcolor) body.style.backgroundColor = localStorage.bgcolor;

// Set on button click
document.querySelectorAll("[data-bgcolor]").forEach(el =>
  el.addEventListener("click", function() {
body.style.backgroundColor = localStorage.bgcolor = this.getAttribute("data-bgcolor");
  })
);
<button data-bgcolor="red">red</button>
<button data-bgcolor="#00f">blue</button>
<button data-bgcolor="white">white</button>

Upvotes: 3

Related Questions