Notifications
Clear all
JavaScript Events
1
Posts
1
Users
0
Reactions
85
Views
Topic starter
18/09/2024 5:38 pm
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>