Search code examples
javascriptcssfunctionstylesheet

Is it possible to change css stylesheets after a page has loaded?


I am trying to add a "dark mode/light mode". I am trying to do this by using two different CSS style sheets and having a single button to click through them

ive tried using setAttribute, innerHTML, removeAtribute( moving the contents of one style sheet into tags and trying to remove one stylesheet)

change to Light Mode

function light(){

    document.getElementById(css).setAttribute("href", "LIGHTMODE.CSS")
    document.getElementById(darkmode).innerHTML="Change to Light Mode"
    document.getElementById(darkmode).onclick="dark()"
    cos
}

function dark(){

            document.getElementById(css).href = "LIGHTMODE.CSS"
            document.getElementById(darkmode).innerHTML="Change to Dark Mode"
            document.getElementById(darkmode).onclick ="light()"
            console.log(darkmode)
    }

It should identify the throught the Id and change the href to whatever is stated


Solution

  • You can have both stylesheets loaded, and enable/disable them at will

    <link rel="stylesheet" href="darkmode.css" class="css dark">
    <link rel="stylesheet" href="lightmode.css" class="css light" disabled>
    
    <script>
        function setcssmode(s) {
            document.querySelectorAll('link.css').forEach(ss => {
                ss.disabled = !ss.classList.contains(s);
            })
        }
        setcssmode('dark');
        setcssmode('light');
    </script>
    

    In this example, the light stylesheet is disabled on page load.

    The benefits of doing it this way is that the stylesheet that is disabled is still loaded on page load, therefore the switch will be instantaneous, rather than potentially delayed while the CSS for the alternative style is loading