JavaScript – Difficulty configuring CSS file from local storage

  • Home / Blog / JavaScript – Difficulty…

JavaScript – Difficulty configuring CSS file from local storage

I am trying to create a theme selector for a web page using two different CSS files. I’ve managed to do this, but over time, I get stuck trying to keep the user’s choice. I’m trying to use local storage to do this but I can’t make it work. This is my HTML and JS code.

    <!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 works will be appreciated.

Write a Comment

Your email address will not be published. Required fields are marked *

x