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
JavaScript Events
JavaScript HTML DOM
JavaScript DOM Manipulation
JavaScript HTML DOM EventListener
JavaScript Forms and Validation
Exercises & Assignments
Write a JavaScript program to change the text of a paragraph on button click
Write a JavaScript program to switch dark mode on and off
Interview Questions & Answers
What is the DOM in JavaScript?
How do you select elements in the DOM?
What are events and event listeners in JavaScript?
What is event bubbling and capturing in JavaScript?
What is event delegation in JavaScript?