I am trying to create a theme selector for a web page using two different css files. I have accomplished to do so but I am stuck when try to make the user selection persist over time. I am trying to use LocalStorage to do so but I can not make it work. This is my html and js code here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet" id="theme-link">
</head>
<body>
<button class="btn-toggle">Themes</button>
<p>At vero eos et accusam et justo duo dolores et ea rebum. </p>
<a href="#">Link</a>
<script>
const btn = document.querySelector(".btn-toggle");
const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") { (theme.getAttribute("href") == "app.css")
theme.href = "appdark.css";
}
const theme = document.querySelector("#theme-link");
btn.addEventListener("click", function() {
if (theme.getAttribute("href") == "app.css") {
theme.href = "appdark.css";
themeName = "dark";
} else {
theme.href = "app.css";
themeName = "light";
}
localStorage.setItem("theme", theme);
});
</script>
</body>
</html>
and both css files here:
/* app.css */
html {
background: #f2f2f2;
}
body {
color: #222;
background: #f2f2f2;
padding: 20px;
}
a {
color: #0033cc;
}
and
/* appdark.css */
html{
filter: invert(1);
}
html {
background: #f2f2f2;
}
body {
color: #222;
background: #f2f2f2;
padding: 20px;
}
a {
color: #0033cc;
}
Any solution that make it work will be appreciated.