2

I want to have a toggle button to switch between a light and dark theme. I can toggle once but it doesn't toggle back after. My current approach is this:

<link id="theme-css" class="dark-theme" rel="stylesheet" href="{% static 'css/dashboard-dark.css' %}">

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="customSwitches" onclick="toggle()">
  <label class="custom-control-label" for="customSwitches">Toggle Theme</label>
</div>

<script>
    function toggle() {
      if(document.getElementById("theme-css").href="{% static 'css/dashboard-dark.css' %}"){
        document.getElementById("theme-css").href="{% static 'css/dashboard-light.css' %}"; 
      }
      else if(document.getElementById("theme-css").href="{% static 'css/dashboard-light.css' %}"){
        document.getElementById("theme-css").href="{% static 'css/dashboard-dark.css' %}"; 
      }
    }
</script>
8
  • 3
    Instead of having two <link> elements in the document, you can have just one and control its "href" attribute value with javascript.
    – MarkSkayff
    Mar 18, 2020 at 17:38
  • 1
    @MarkSkayff I have updated my post
    – GTA.sprx
    Mar 18, 2020 at 18:13
  • You can prepend a class name for themes and load both files. Then you can toggle the body class. Like .dashboard-dark .style {} and .dashboard-light .style {} and <body="dashboard-dark"> etc.. Your css will be larger but you may lose the loading effect while changing themes.
    – erdimeola
    Mar 18, 2020 at 18:16
  • 1
    based on your code, the if statement will always evaluate to true because you are doing assignment not checking for equality using == or ===
    – ROOT
    Mar 18, 2020 at 18:19
  • 1
    @MarkSkayff Those are Django template tags
    – GTA.sprx
    Mar 18, 2020 at 18:33

1 Answer 1

0

Let's see. First to note you are looking for a toggle type functionality. When you do a toggle you want to keep state somewhere. Whether on an html element itself or within javascript object.

I would load the script with an initial state for a theme. Let's say the light theme and store that value within a javascript variable.

So, everytime the toggle function is called, you query the js variable state, and you swap the themes according to that.

So you would do something like this:

// Some variable called state holds the theme state
var link = document.getElementById("theme-css");
if(state == 'light')
     link.href = "<the-dark-uri-css-path>";
else
     link.href = "<the-light-uri-css-path>";
// The you toggle the state val
state = state=='light'? 'dark' : 'light';

Remember you can build this as an object and keep the state of the theme within an object property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.