Skip to content
Home » Forum

Forum

Dark Mode Toggle (U...
 
Notifications
Clear all

Dark Mode Toggle (Using Click Event)

1 Posts
1 Users
0 Reactions
71 Views
Mark Sikaundi
(@emmanuelmark117)
Member Admin
Joined: 2 years ago
Posts: 101
Topic starter  

Add a button that toggles between light and dark modes by changing the page’s background and text colors.

Use Case: Dark Mode Switch

Allow users to toggle between light and dark modes with a button click.

Example:

<button id="darkModeToggle">Toggle Dark Mode</button>

<script>
  const toggleButton = document.getElementById('darkModeToggle');
  let darkModeEnabled = false;

  toggleButton.addEventListener('click', function() {
    if (!darkModeEnabled) {
      document.body.style.backgroundColor = 'black';
      document.body.style.color = 'white';
      toggleButton.textContent = "Toggle Light Mode";
    } else {
      document.body.style.backgroundColor = 'white';
      document.body.style.color = 'black';
      toggleButton.textContent = "Toggle Dark Mode";
    }
    darkModeEnabled = !darkModeEnabled;
  });
</script>

   
Quote
Share: