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>
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
});