skip to Main Content

The following script is the code for a dark mode toggle on my website.

I don’t really know Javascript (I only know Python), so writing this code was a challenge and it might be poorly written. But what it does is it checks for a session variable "is_dark_mode" using Django Templating Language, to check if the current user has previously set his view to light or dark mode, and then it proceeds to switch the Boolean for that variable and adds or removes a "dark-mode" class to the body of my HTML (which is how I’m switching styles when in dark mode).

It works fine in Chrome, but it doesn’t work at all in Safari, and I don’t know why. When using the JavaScript console, it throws an error:

SyntaxError: Unexpected token ';'

This SyntaxError is pointing to this line of code:

var darkMode = ;

Could someone give me a hand in figuring this out? I’m learning backend only, so I got no idea of how to solve this, and I’ve already tried googling it, with no success.

<script>
      document.addEventListener("DOMContentLoaded", function () {
        var modeToggle = document.getElementById("modeToggle");

        function setInitialDarkMode() {
          var darkMode = {{ request.session.is_dark_mode|default_if_none:"false"|lower }};
          modeToggle.checked = darkMode;

          if (darkMode) {
            document.body.classList.add("dark-mode");
          }
        }

        modeToggle.addEventListener("change", function () {
          var darkMode = modeToggle.checked;

          fetch("{% url 'toggle-mode' %}", {
            method: 'POST',
            headers: {
              'X-CSRFToken': '{{ csrf_token }}',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ dark_mode: darkMode }),
          })
            .then(response => response.json())
            .then(data => {
              if (darkMode) {
                document.body.classList.add("dark-mode");
              } else {
                document.body.classList.remove("dark-mode");
              }
              console.log(data);
            })
            .catch(error => console.error(error));
        });

        setInitialDarkMode();

      });
</script>

2

Answers


  1. It looks like the issue in your code is related to how you are initializing the darkMode variable. The error you are seeing, "SyntaxError: Unexpected token ‘;’", is because you have this line:

    var darkMode = ;
    

    The variable darkMode is being initialized without a value, and that’s causing a syntax error. To fix this issue, you should remove the line:

    var darkMode = ;
    

    Instead, you should set the darkMode variable inside the setInitialDarkMode function using the value from your Django template. Your code should look like this:

    function setInitialDarkMode() {
      var darkMode = {{ request.session.is_dark_mode|default_if_none:"false"|lower }};
      modeToggle.checked = darkMode;
    
      if (darkMode) {
        document.body.classList.add("dark-mode");
      }
    }
    

    This code correctly initializes the darkMode variable based on the value from your Django template. Make sure you don’t have any extraneous characters or missing values in your Django template variable {{ request.session.is_dark_mode|default_if_none:"false"|lower }}, as it should provide a valid JavaScript boolean value (either true or false) for this code to work correctly.

    Once you make this change, your code should work as expected in Safari and other browsers.

    Login or Signup to reply.
  2. another way of doing the same as mentioned earlier

    function checkSessionVariable() {
      var darkMode = "{{ request.session.is_dark_mode|default_if_none:"false"|lower|default:"false" }}";
      if (darkMode === "true") {
        // for calling setInitialDarkMode() or setting the toggle to true
        setInitialDarkMode();
      }
    }
    
    document.addEventListener("DOMContentLoaded", function() {
      var modeToggle = document.getElementById("modeToggle");
      
      // Calling checkSessionVariable() function on page load
      checkSessionVariable();
      
      // put all other code
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search