<button id="themeToggle">Toggle Theme</button>
<p>Hello! This text will change theme.</p>
<style>
body {
background: white;
color: black;
}
body.dark {
background: black;
color: white;
}
</style>
<script>
// Get saved preference (if any)
let userPref = localStorage.getItem("theme");
document.cookie = "theme=light; path=/";
// Apply saved preference
if (userPref === "dark") {
document.body.classList.add("dark");
document.cookie = "theme=dark; path=/";
}
// Button click event
document.getElementById("themeToggle").addEventListener("click", () => {
document.body.classList.toggle("dark");
// Save user preference
if (document.body.classList.contains("dark")) {
localStorage.setItem("theme", "dark");
document.cookie = "theme=dark; path=/";
} else {
localStorage.setItem("theme", "light");
document.cookie = "theme=light; path=/";
}
});
</script>
how to create user preference in JavaScript on webpage click
September 11, 2025 in Javascript, Tips and Tricks