Home > OS >  Dark mode on-off button with checkbox
Dark mode on-off button with checkbox

Time:08-16

Console.logs are not showing. And my functions are not working. I tried several different functions and solutions but none of them worked for me. Where is the problem can anyone help?

this my html

<div >
              <input type="checkbox" name="checkbox" id="darkmodeonoff" />
              <label for="darkmodeonoff"></label>
            </div>

this my js;

var checkbox = document.querySelector("input[name=checkbox]");
    console.log(checkbox);

    checkbox.addEventListener("change", (e) => {
      if (e.target.checked) {
        darkmode();
        console.log("Checkbox is checked..");
      } else {
        darkmodeoff();
        console.log("Checkbox is not checked..");
      }
    });

CodePudding user response:

bro where is your darkmode() and darkmodeoff() functions? Try add them like at the below and check out are you gonna get any alert or not? Also if you see any warning on the console, please share

 const darkmode = () =>{
        alert('dark')
    }
    const darkmodeoff = () =>{
        alert('light')
    }

CodePudding user response:

You can let darkmode and darkmodeoff log what you want

const darkmode = () =>{
    console.log("Checkbox is checked..");
}
const darkmodeoff = () =>{
    console.log("Checkbox is not checked..");
}

Then call it using if statement

if (e.target.checked) {
    darkmode();
  } else {
    darkmodeoff();
  }
});

CodePudding user response:

Try using classList.toggle:

checkbox.addEventListener("change", (e) => {
      const example = document.querySelector('.containerThatYouWantUse')
      example.classList.toggle('darkModeClass')
    });
  • Related