John Kerby
John Kerby

Reputation: 83

Comment out CSS stylesheet dynamically?

I have built pretty heavy light and dark modes with localstorage for a website. Switching from one to the other is seamless and both look amazing. Yet, i have flickering issues when navigating the dark mode.

Both style sheets reside in this order upwards in my header.php


    <link id="light" rel="stylesheet" type="text/css" title="day" href="https://example.com/public/css/main.css">
    <link id="dark" rel="stylesheet" type="text/css" title="night" href="https://example.com/public/css/night.css">

The localstorage switches are handled with javascript downwards in the same file.

After trying a million things, turns out to be that when i comment out the first stylesheet mentioned above, the flickering disappears and the browsing is seamless.

So my question would be: How can i comment out the first stylesheet line with some javascript command that would be added to the localstorage section? Or is there another way to comment out that stylesheet dynamically?

Here ist the localstorage function where i would need it to be inside:

<script>
document.getElementById("light").href = localStorage.getItem('light');
document.getElementById("dark").href = localStorage.getItem('dark');

function dayoff() {
document.getElementById("light").href = 'https://example.com/public/css/night.css';
    localStorage.setItem( 'light', 'https://example.com/public/css/night.css' );
document.getElementById("light").href = 'https://example.com/public/css/night.css';
    localStorage.setItem( 'dark', 'https://example.com/public/css/night.css' );
document.getElementById("logo").src = 'https://example.com/public/img/toplogo-night.png';
    location.reload();
}
</script>

Upvotes: 0

Views: 90

Answers (1)

Webdeveloper_Jelle
Webdeveloper_Jelle

Reputation: 2856

You should keep what mode the user is using (light or dark)

localStorage.setItem('mode', 'light or dark');

Then you should add the stylesheet based on what mode the user is using.

Your function

function dayoff() {
   // toggle function 
   if(localStorage.getItem("mode") === null || localStorage.getItem("mode") == "light"){
       localStorage.setItem("mode", "dark");
   }
   else{
       localStorage.setItem("mode", "light");
   }
   location.reload();
}
if(localStorage.getItem("mode") === null){
   // first time visitors
    $('head').append('<link id="light" rel="stylesheet" type="text/css" href="https://example.com/public/css/main.css">');
}
else{
   // returning users
   if(localStorage.getItem('mode') == "light"){
      $('head').append('<link id="light" rel="stylesheet" type="text/css" href="https://example.com/public/css/main.css">');
   }
   else{
      $('head').append('<link id="dark" rel="stylesheet" type="text/css" href="https://example.com/public/css/dark.css">');
   }
}

Upvotes: 2

Related Questions