2

I have this piece of code:

$(document).ready(function() {
    $(".lightDark").hide();
    $("#changeTheme").click(function() {

        $(".lightDark").toggle("slow");
    });

    // Switch theme

    $('#lightTheme').click(function() {
         $('link[href="darkMode.css"]').attr('href','lightMode.css');
    });

    $('#darkTheme').click(function() {
        $('link[href="lightMode.css"]').attr('href','darkMode.css');
    });
}); 
    
body {
background-color: black;
}

.changeThemeButtons {
  float: right;
  margin-top: 50px;
  margin-right: 50px;
  border:2px solid white;
  border:none;
  color:white;
}

.changeThemeButtons td {
  font-family: 'Open Sans Condensed', sans-serif;
  font-size: 1.6em;
  text-transform: uppercase;
  color:white;
  text-align: center;
}

.changeThemeButtons th {
  background-color: #733FFF;
  border-radius: 100px;
  height:200px;
  width:200px;
}

#changeTheme {
  cursor: pointer;
}

#changeTheme i {
  color:#f00;
}

#darkTheme {
  color:black;
  margin-right: 50px;
}

#lightTheme {
  color:white;
}
<script src="https://kit.fontawesome.com/c22b2f5999.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" id="darkMode" href="darkMode.css">


<div class="block two">
         <nav>
            <a href="#about">About me</a>
            <a href="#myWork">My Work</a>
            <a href="#services">Services</a>
            <a href="#contact">Contact</a>
         </nav>
         
         
         <table class="changeThemeButtons" align="right">
            <tr>
               <td><a id="changeTheme">Change Theme &nbsp;<i class="fas fa-caret-down"></i></a></td>
            </tr>
            <tr>
               <th class="lightDark">
                  <a href="#" id="darkTheme"><i class="fas fa-circle fa-3x"></i></a> 
                  <a href="#" id="lightTheme"><i class="fas fa-circle fa-3x"></i></a>
               </th>
            </tr>
         </table>

Everything works fine, until the point where you're on lightMode.css and let's say you refresh the page, then it would reset to the darkMode.css. I have tried to remove the default darkMode.css from HTML (with JQuery), but it doesn't seem to work. I need it to stay to lightMode (if selected) until you'd click again to change to darkMode manually.

ergoProxy
  • 93
  • 9
  • 3
    Consider session variables or cookies to store the css state. – Rob Moll Jan 22 '20 at 19:53
  • it is expected to every refresh that all things got "refreshed" to starting point, since all scripts and code are loaded again. You probably would need to save the user choice in the [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) when user chooses and then read it from localStorage on page startup – Calvin Nunes Jan 22 '20 at 19:53
  • You could set a a flag in local storage and then check that flag on page load to only enable light or dark mode – Nicholas Siegmundt Jan 22 '20 at 19:53
  • 1
    this can help: https://stackoverflow.com/questions/23699556/using-cookies-to-retain-stylesheet-preference-across-website – Calvin Nunes Jan 22 '20 at 20:54
  • localStorage.setItem('myCat', 'Tom'); var cat = localStorage.getItem('myCat'); works like session – Stefan Avramovic Jan 22 '20 at 20:55
  • Right... That seems easy enough, but how do i implement that into my code? @StefanAvramovic – ergoProxy Jan 23 '20 at 21:10
  • @DianaCristina Check out my answer, does this solve your problem? – Stefan Avramovic Jan 24 '20 at 11:57

3 Answers3

1

Just put your theme css in a css file and pass it to the function, On page load the if (localStorage.getItem("theme") != "") checks if theme has been set.. Here you have an example:

    if (localStorage.getItem("theme") != "") {
        loadcssfile(localStorage.getItem("theme"));
      }

      function loadcssfile(filename) {
        if (filename != "") {
          localStorage.setItem("theme", filename);
        }
        
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);

        if (typeof fileref != "undefined")
          document.getElementsByTagName("head")[0].appendChild(fileref);
      }
  <div onclick="loadcssfile('css/pink.css')" id="pink">
      Pink
    </div>
    <div
      onclick="loadcssfile('css/blue.css')" id="blue">
      Blue
    </div>
Stefan Avramovic
  • 1,365
  • 2
  • 11
  • 20
0
  1. You need to provide a default theme for first time visitor.
  2. You need to store the user selection somewhere (cookie, local storage or database etc.)
  3. On on document ready, read the user's preferred theme from your storage and apply the corresponding css file. If there is no preference, just leave the default theme.
Ankit
  • 680
  • 4
  • 17
  • Thank you, @Ankit. I was hoping I wouldn't need to do that kind of stuff because I have no clue how do to it. Could you guide me further in any way? So basically my question is, how would I store the user's selection on local storage for example? – ergoProxy Jan 22 '20 at 20:10
  • I assume you do not have a database, so you can save user's selection in a cookie and then read it on page load. Here is a link that talks about handling cookies. https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript – Ankit Jan 22 '20 at 20:18
0

You may do something like below to store the value in localstorage:

$(document).ready(function() {

  const theme = localStorage.getItem('mode');
  console.log(theme);
  if(theme){
    $('link[id="darkMode"]').attr('href',theme);
 }
    $("#changeTheme").click(function() {

        $(".lightDark").toggle("slow");
    });

    // Switch theme

    $('#lightTheme').click(function() {     
         $('link[id="darkMode"]').attr('href','lightMode.css');
      localStorage.setItem('mode','lightMode.css');
    });

    $('#darkTheme').click(function() {
        $('link[id="darkMode"]').attr('href','darkMode.css');
        localStorage.setItem('mode','darkMode.css');
    });
}); 
    
Vishnu
  • 897
  • 6
  • 13