Syntax error How to switch between dark and light mode with CSS and JavaScript?\\n

How to switch between dark and light mode with CSS and JavaScript?\\n



To switch between dark and light mode with JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      padding: 25px;
      background-color: white;
      color: black;
      font-size: 25px;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .dark-mode {
      background-color: black;
      color: white;
   }
   .toggleButton {
      padding: 12px;
      font-size: 18px;
      border: 2px solid green;
   }
</style>
</head>
<body>
<h1>Toggle Dark/Light Mode Example</h1>
<button class="toggleButton">Toggle dark mode</button>
<h2>Click the above button to toggle dark mode</h2>
<script>
   document .querySelector(".toggleButton") .addEventListener("click", toggleDarKMode);
   function toggleDarKMode() {
      var element = document.body;
      element.classList.toggle("dark-mode");
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the “Toggle dark mode” button −

Updated on: 2020-05-08T13:26:19+05:30

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements