Help with Toggle Button code in VS Code

Hello Everyone,

I am currently trying to create a toggle button (switch) that would change the background to dark mode. I have written it in code pen (Toggle Button) and it works, but when I put it in my VS Code test area it doesn’t work. I checked the link and script tags and they were correct, and just to make sure I put the code directly in the script tag and it still didn’t work. Do you guys have any suggestions what is wrong or what I should do to fix this problem?

In what way doesn’t it work? What problems are you seeing?

The Java Script portion is not taking effect. Everything about the toggle button itself works like it should, and I tested the css by changing the body’s class to dark and it worked, it’s just the JavaScript that is giving me the problem.

Try wrapping your JavaScript in

document.addEventListener("DOMContentLoaded", (event) => {
// register your listeners
}
1 Like

There was no change.

Just to be clear, this is what you ment: Correct?

document.addEventListener("DOMContentLoaded", (event) => {
    document.querySelector('button').addEventListener('click', () => {
    document.body.classList.toggle('dark');
})})

You forgot the . in your querySelector.

1 Like

Alternatively, you could make your toggle function a named function, for example toggleMode and then remove the event registration from the JavaScript and add onclick="toggleMode()" to the button.

Both will work.

The problem is (besides the typo) that your JavaScript runs before the page has loaded, so there is .button element to select and register an event on. The event listen for the DOM to be loaded delays this registration until the DOM exists.

1 Like

It works now, lol, I guess I changed something in the process.

Thanks :smile:

Congratulations on your toggle button. Keep up the good work!

Thanks again :smile:

I’ll put a defer in the script tag to fix that problem :slightly_smiling_face:

Stupid Question:

Is this the correct way to put the JavaScript function that I was having trouble with int to React?

function App() {

  document.addEventListener("DOMContentLoaded", (event) => {
    document.querySelector('.button').addEventListener('click', () => {
    document.body.classList.toggle('dark');
})})

  return (
    <div>
    <label class="switch">
        <input class="button" type="checkbox" />
        <span class="slider round"></span>
    </label>
    </div>
  );
}

export default App;

I’m not sure if it’s right, but I put the document event listener in another event listener called “DOMContentLoded” and put it in a script tag in the html doc and it worked. I guess that is what they mean when they say that it’s held up with duck tape and a prayer, lol :laughing: