0

I am creating a website as front-end practice (I am a beginner). I have figured out how to use JS to toggle between two css color styles. However, when I click to go onto a new page, the theme of the previous page is not remembered, meaning it reverts back to the original theme. So for example, on my home page I have the dark theme by default, I click the toggle button to active light mode, then it switches, but when I click to the next page, it's by default the dark mode. How do I fix this? I think I need to store the state of the theme somewhere that can remember the state over the pages, but I do not know how to do that. Necessary code is attached below:

<!DOCTYPE html>
<html>
    <head> 
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>
    <header>
        <div class="container">
        <img src="paint-brush-icon-10-inverted.png" id = "icon" alt="" style="width: 35px; position:relative; top:20px; left: 20px;">
        <nav>
            <ul>
                <li><a class="navbar"  href="home.html">Home</a></li>
                <li><a class="navbar" href="introduction2.html">Introduction</a></li>
                <li><a class="navbar" href="experience-education2.html">Experience and education</a></li>
                <li><a class="navbar" href="portfolio.html">Portfolio</a></li>
                <li><a class="navbar" href="contactme.html">Contact Me</a></li>

            </ul>
        </nav>

        </div>

    </header>
        <hr>

     // code unimportant here
        
    <script> 
    
        var icon = document.getElementById("icon");
        icon.onclick = function(){
            document.body.classList.toggle("altmode");
                if(document.body.classList.contains("altmode")){
                    icon.src = "paint-brush-icon-10.png";
                    profile.src = "profile-pic (13).png";
                }else {
                    icon.src = "paint-brush-icon-10-inverted.png";
                    profile.src = "profile-pic (12).png";
                }
        }

    </script>    
    </body>
</html>

I don't know how to make pages communicate. I tried to get the page I click on to check whether the previous page had light or dark theme, but I couldn't figure it out.

callumgilf
  • 11
  • 1
  • 1
    Does this answer your question? [How to store objects in HTML5 localStorage/sessionStorage](https://stackoverflow.com/questions/2010892/how-to-store-objects-in-html5-localstorage-sessionstorage) – jabaa Oct 27 '22 at 13:02

1 Answers1

2

Just use localStorage. To save it across browser sessions just set the light theme as follows: localStorage.setItem('theme', 'light'). And to retrieve it from the pages that you want: const theme = localStorage.getItem('theme').