How do i set dark mode accross pages instead of user having to manually press it on every single page

Viewed 78

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>
3 Answers

localStorage The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.

var icon = document.getElementById("icon");
// on page load event we can use previous theme value
window.onload = function() {
    initTheme();
};

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

// on icon element click we check the localstorage item 'theme' value to control which theme we should use
icon.onclick = function() {
    localStorage.getItem('theme') === 'dark' ? localStorage.setItem('theme', '') : localStorage.setItem('theme', 'dark');
    initTheme();
}

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>

Have a setting page where user can select the settings they like and save it on the database.

Then load it on a session variable as they login.

Update that session variable should they change it while logged-in.

Either have a separate setting page or include it on their profile page. Profile page is where they can change email, password, avatar, etc.

Related