Write a JavaScript program to switch dark mode on and off

Description: Create a button that switches the page between light and dark colours.

Hint:

  • Make a CSS class .dark with dark colours.
  • Use classList.toggle("dark") on the body.

Toggle dark mode

<style>
  body { background: white; color: black; }
  body.dark { background: #1e1e1e; color: #f5f5f5; }
</style>

<button id="toggle">Toggle dark mode</button>

<script>
  document.getElementById("toggle").addEventListener("click", () => {
    document.body.classList.toggle("dark");
  });
</script>

Output:

Output in the browser

The page after one click (dark class added).

How it works

  • classList.toggle("dark") adds the class if it is missing, and removes it if it is there.
  • The CSS rule body.dark then changes the colours. Each click switches again.
  • The box above shows the dark state.

Read HTML DOM and CSS Variables.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.