I am trying to implement a light/dark theme toggle to my website, but I'm running into issues with the checkbox I'm using for the toggle. Here is the HTML:
<input type="checkbox" id="theme-switch" name="theme"/>
<label for="theme-switch"><img src="./images/theme-switch-light.png" alt="Theme"/></label>
And here are some stabs I took at the JavaScript (based on this tutorial and this S/O thread):
// without jQuery
const themeCheckbox = document.querySelector("input[name=theme]");
themeCheckbox.addEventListener('change', () => {
if (this.checked) {
console.log('dark');
} else {
console.log('light');
}
});
// with jQuery (take 1)
$('input[name=theme]').change(() => {
if($(this).is(':checked')) {
console.log('dark');
} else {
console.log('light');
}
});
// with jQuery (take 2)
$('#theme-switch').change(() => {
if($(this).is(':checked')) {
console.log('dark');
} else {
console.log('light');
}
});
The issue is that all of these always print 'light', both when the box is checked and unchecked. This means that it is correctly retrieving the element and triggering the .change() method, but for some reason it always thinks the value is unchecked. I referenced this S/O thread and tried the suggested answer, but it did not work for me. Any ideas?