Sling Academy
Home/JavaScript/Light and Dark Mode Switcher Using the JavaScript DOM

Light and Dark Mode Switcher Using the JavaScript DOM

Last updated: December 10, 2024

Creating a light and dark mode switcher is a popular task for modern web development as it enhances user experience significantly. Implementing this feature involves using JavaScript DOM to dynamically change styles based on user preference. In this article, we will guide you through the process of developing a simple light and dark mode switcher using HTML, CSS, and JavaScript.

Setting Up the HTML Structure

Let's begin by setting up a simple HTML structure. For this example, we'll include a button to toggle between modes and a basic content area.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Light/Dark Mode Switcher</title>
</head>
<body>
    <div class="content">
        <h1>Welcome to My Website</h1>
        <p>This is a sample text content for demonstration purposes.</p>
    </div>
    <button id="mode-switcher">Switch Mode</button>
    <script src="script.js"></script>
</body>
</html>

Designing with CSS

Next, style the page using CSS for both light and dark modes. Use CSS variables to easily switch between color themes.

:root {
    --bg-color-light: #ffffff;
    --text-color-light: #000000;
    --bg-color-dark: #333333;
    --text-color-dark: #ffffff;
}

body {
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
    background-color: var(--bg-color-light);
    color: var(--text-color-light);
    transition: background-color 0.5s, color 0.5s;
}

.dark-mode {
    background-color: var(--bg-color-dark) !important;
    color: var(--text-color-dark) !important;
}

button {
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 10px 20px;
    cursor: pointer;
}

Implementing JavaScript for Mode Switching

With HTML and CSS set, we'll use JavaScript to add interactive functionality that toggles between light and dark modes. We'll add an event listener to the button that modifies the classes of the HTML body.

document.addEventListener("DOMContentLoaded", function() {
    const modeSwitcher = document.getElementById('mode-switcher');
    const body = document.body;

    modeSwitcher.addEventListener('click', function() {
        body.classList.toggle('dark-mode');
        updateButtonText();
    });

    function updateButtonText() {
        if (body.classList.contains('dark-mode')) {
            modeSwitcher.textContent = "Switch to Light Mode";
        } else {
            modeSwitcher.textContent = "Switch to Dark Mode";
        }
    }

    // Initialize button text based on the current mode
    updateButtonText();
});

Enhancing User Experience

To further enhance user experience, consider saving user preferences using localStorage. This allows the preferred mode to persist even when the user reloads the page or revisits the site.

document.addEventListener("DOMContentLoaded", function() {
    const modeSwitcher = document.getElementById('mode-switcher');
    const body = document.body;
    const currentMode = localStorage.getItem('mode');

    if (currentMode && currentMode === 'dark') {
        body.classList.add('dark-mode');
    }

    modeSwitcher.addEventListener('click', function() {
        body.classList.toggle('dark-mode');
        const mode = body.classList.contains('dark-mode') ? 'dark' : 'light';
        localStorage.setItem('mode', mode);
        updateButtonText();
    });

    function updateButtonText() {
        if (body.classList.contains('dark-mode')) {
            modeSwitcher.textContent = "Switch to Light Mode";
        } else {
            modeSwitcher.textContent = "Switch to Dark Mode";
        }
    }

    updateButtonText();
});

By following these steps, you create a responsive light and dark mode toggle for your website. This simple yet effective UI enhancement ensures that users can personalize their browsing experience, optionally saving these preferences for future visits.

Next Article: Focus and Blur Events: Managing Input Fields in JavaScript

Previous Article: Shortcuts with querySelectorAll(): Targeting Multiple Elements in JavaScript

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration