Home > Blockchain >  How do i set dark mode accross pages instead of user having to manually press it on every single pag
How do i set dark mode accross pages instead of user having to manually press it on every single pag

Time:05-25

I am making a Website for my Uni project which requires 5 pages.

This is my code for setting dark mode in the home page, but when I go to the second page I need to manually press the button to get the dark mode on again rather than it sustaining the information from the home page.

   <img src="DM.png" id="icon">

 </div>


<script type="text/javascript">
    
    var icon = document.getElementById("icon");

    icon.onclick = function() {
        document.body.classList.toggle("darktheme");
        if (document.body.classList.contains("darktheme")) {
            icon.src="LM.png";
        }else
            icon.src="dm.png";

    }
</script>

CodePudding user response:

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage[localStorage][1]

window.onload = function() {
    initTheme();
};
function initTheme() {
    const theme = localStorage.getItem('theme');
        if (theme == 'dark') {
            icon.src="LM.png";
        } else {
            icon.src="dm.png";
        }
}

var icon = document.getElementById("icon");
icon.onclick = function() {
    localStorage.getItem('theme') === 'dark' ? localStorage.setItem('theme', '') : localStorage.setItem('theme', 'dark');
    initTheme();
}

CodePudding user response:

The only thing that you have to do is store your theme insidedocument.cookie. This is the code that you need:

<img src="DM.png" alt="OPS!" id="icon" />

<script type="text/javascript">

    var icon = document.getElementById("icon");
    //Theme saves here
    var theme = /theme/.test(document.cookie) ? document.cookie.split("theme=")[1].split(';')[0] : "whitetheme";

    //Load theme at first
    window.onload = function () {
        if (theme == "darktheme") {
            document.body.classList.add("darktheme");
        }
    };

    icon.onclick = function () {
        document.body.classList.toggle("darktheme");
        if (document.body.classList.contains("darktheme")) {
            icon.src = "LM.png";
            theme = "darktheme";
        } else {
            icon.src = "dm.png";
            theme = "whitetheme"
        }

        //Save theme and expire time
        var date = new Date();
        document.cookie = "theme="   theme   ";expires="   date.setTime(date.getTime()   (365*24*60*60*1000))   ";path=/"
    }

</script>
  • Related