💻

JavaScript Toggle Dark Mode Tutorial

Jul 17, 2024

JavaScript Toggle Dark Mode Tutorial

Introduction

  • Demo: Clicking an icon toggles background between dark and light mode.

Project Setup

  • Files Created: index.html, styles.css, script.js
  • Link: CSS and JS files linked in HTML.

HTML

  • Created a title: JavaScript Toggle Dark Mode.
  • Used Bootstrap icons (link provided in the video description).
  • Icon Used: Sun (search and copy from Bootstrap Icons).
  • Code Snippet: <i id="toggle-icon" class="bi-brightness-high"></i>

CSS Styling

  • Body:
    • margin: 0;
    • padding: 0;
    • font-family: Arial;
  • Icon (i tag):
    • font-size: 15px;
    • cursor: pointer;
    • position: absolute; top: 15px; left: 15px; transform: translate(-15%, -15%);
  • Heading (h1 tag):
    • text-align: center;
    • font-size: 3em;

JavaScript

  • Variables:
    • const toggle = document.getElementById('toggle-icon');
    • const body = document.querySelector('body');
  • Event Listener: Added click event listener to icon.
    • Toggles between two icons and background colors.
  • If-Else Conditions:
    • If bi-brightness-high is the class, change to bi-moon icon and switch to dark mode.
    • Else, revert to light mode.
  • Code Snippet: toggle.addEventListener('click', function() { if (toggle.classList.contains('bi-brightness-high')) { toggle.classList.remove('bi-brightness-high'); toggle.classList.add('bi-moon'); body.style.backgroundColor = 'black'; body.style.color = 'white'; } else { toggle.classList.remove('bi-moon'); toggle.classList.add('bi-brightness-high'); body.style.backgroundColor = 'white'; body.style.color = 'black'; } body.style.transition = 'all 2s'; });

Conclusion

  • Summary: The tutorial covers toggling dark and light modes using JavaScript.
  • Main Steps: Setting up HTML, CSS, and JS, adding event listeners, and implementing If-Else logic for toggle.

Final Remarks

  • Encouragement: Follow along and practice to get comfortable with toggling techniques.
  • Future Projects: Stay tuned for more JavaScript projects.