mercredi 15 décembre 2021

Theme switcher not working - Uncaught TypeError: checkbox is null [duplicate]

The problem:


When i click the "checkbox" it's supposed to change the theme of the website, but it't prints out an error in the console.

Uncaught TypeError: checkbox is null

I watched many videos but it still wouldn't work.

Sources:

-Html

<label id="colorswitch" for="switcher">
   <input type="checkbox" id="switcher">
   <span class="slider round"></span>
</label>
<p class="switchtext">Light mode</p>

-CSS

:root {
   --linkcolor: rgb(241, 165, 0);
   --bgcolor: rgb(30, 30, 30);
   --gridbgcolor: rgb(40, 40, 40);
   --textcolor: rgb(220, 220, 220);
   --logobgcolor: rgb(80, 80, 80);
   --logobghovercolor: rgb(110, 110, 110);
}

body[data-theme="light"] {
   --linkcolor: rgb(220, 220, 220);
   --bgcolor: rgb(220, 220, 220);
   --gridbgcolor: rgb(220, 220, 220);
   --textcolor: rgb(220, 220, 220);
   --logobgcolor: rgb(220, 220, 220);
   --logobghovercolor: rgb(220, 220, 220);
}

-Javascript

const checkbox = document.getElementById('switcher');
checkbox.addEventListener('change', (e) => {
    if (e.target.checked) {
        document.body.setAttribute('data-theme', 'light')
    } else {
        document.body.setAttribute('data-theme', 'dark');
    }
});


if (e.target.checked) {
    document.documentElement.setAttribute('data-theme', 'light');
    localStorage.setItem('theme', 'light');
}
else {
    document.documentElement.setAttribute('data-theme', 'dark');
    localStorage.setItem('theme', 'dark');
}



Aucun commentaire:

Enregistrer un commentaire