Solution 1 :

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>";
     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.

Problem :

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>

    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' %}"; 


Comment posted by MarkSkayff

Instead of having two elements in the document, you can have just one and control its “href” attribute value with javascript.

Comment posted by GTA.sprx

@MarkSkayff I have updated my post

Comment posted by erdimeola

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 etc.. Your css will be larger but you may lose the loading effect while changing themes.

Comment posted by ROOT

based on your code, the if statement will always evaluate to true because you are doing assignment not checking for equality using

Comment posted by GTA.sprx

@MarkSkayff Those are Django template tags