0

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?

  • When you are using `this` you have to be careful about what scope you are in. Because you are using arrow functions, `this` does not refer to the checkbox. Check the question yours is marked as a duplicate of for more information on that. And if you change your arrow functions to normal functions like your linked question is, it should work as you expect. – nrayburn-tech May 05 '20 at 04:02
  • Yup, I read that question and realized I should be using normal functions, and it worked! Silly mistake... but thank you! – user11591069 May 05 '20 at 04:15

0 Answers0