Creating a Simple Dark Mode Toggle with HTML, CSS, and JavaScript

Dark mode has become an essential feature in modern web design, providing users with a visually comfortable experience, especially in low-light environments. In this blog post, we’ll walk through a simple yet effective dark mode toggle using HTML, CSS, and JavaScript.

Why Implement Dark Mode?

Dark mode reduces eye strain, saves battery life on OLED screens, and enhances the overall user experience. Many popular websites and apps now offer dark mode options, making it a must-have feature for any website.

Building the Dark Mode Toggle

We’ll be creating a simple web page that includes a dark mode switch. The implementation involves:

  • HTML to structure the page and the toggle switch.
  • CSS to style both the light and dark modes.
  • JavaScript to enable user interaction and save preferences.

1. The HTML Structure

We begin with a basic HTML document that contains a toggle switch for dark mode and some sample text to observe the effect.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Mode Toggle</title>
    <link rel="stylesheet" href="theme-switcher.css">
    <script defer src="theme-switcher.js"></script>
</head>
<body>
    <div class="theme-toggle">
        <span>Light</span>
        <label class="switch">
            <input type="checkbox" id="theme-switcher">
            <span class="slider round"></span>
        </label>
        <span>Dark</span>
    </div>
    <div class="container">
        <h1>Welcome to Dark Mode Switcher</h1>
        <p>Try switching to dark mode to see the effect!</p>
    </div>
</body>
</html>

2. Styling the Dark Mode with CSS

We use CSS to define styles for both light and dark modes, ensuring smooth transitions when toggling between them.

body {
    font-family: Arial, sans-serif;
    transition: background 0.3s, color 0.3s;
    padding: 20px;
}

.dark-mode {
    background-color: #121212;
    color: #ffffff;
}

.switch {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 24px;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 34px;
}

.dark-mode .slider {
    background-color: #555;
}

Step 3: JavaScript Logic

Finally, we add JavaScript to handle the toggle functionality and store the user’s preference.

 document.addEventListener("DOMContentLoaded", function() {
            const themeSwitcher = document.getElementById("theme-switcher");
            const currentTheme = localStorage.getItem("theme") || "light";
            
            if (currentTheme === "dark") {
                document.body.classList.add("dark-mode");
                themeSwitcher.checked = true;
            }
            
            themeSwitcher.addEventListener("change", function() {
                if (this.checked) {
                    document.body.classList.add("dark-mode");
                    localStorage.setItem("theme", "dark");
                } else {
                    document.body.classList.remove("dark-mode");
                    localStorage.setItem("theme", "light");
                }
            });
        });

Conclusion

With just a few lines of HTML, CSS, and JavaScript, we’ve successfully implemented a dark mode toggle for a webpage. This simple approach enhances user experience and adds a modern touch to any website. Try it out and customize it to fit your needs!

Working Codepen Demo

See the Pen Auto Dark Mode by Mossawir (@mossawir) on CodePen.

Ready to bring your vision to life? Let's start your web development project today!

Latest Posts

Check out my latest blog posts for valuable insights, tips, and trends in web development and design that can help elevate your projects!

At Mossawir.com, we are committed to protecting the privacy of our clients and website visitors. This Privacy Policy outlines how I collect, use, and protect your personal information when you visit our website or engage with our services.

1. Information I Collect

I collect the following types of information to provide better services to our clients:

  • Personal Information: This includes your name, email address, phone number, and any other information you provide through contact forms or when communicating with us.
  • Technical Information: I may collect data such as your IP address, browser type, device information, and browsing behavior through cookies and similar tracking technologies.
  • Project Information: If you engage our services, we may collect information related to your project requirements, design preferences, and other specifications necessary for the development process.

2. How We Use Your Information

I use the collected information to:

  • Provide and manage our services, including responding to inquiries and completing projects.
  • Improve the functionality and user experience of our website.
  • Communicate with you about project updates, support, or any other relevant information.
  • Ensure the security and protection of our website and services.

I do not sell or rent your personal information to third parties. Your information will only be shared when necessary to fulfill your project requirements or comply with legal obligations.

3. Cookies and Tracking Technologies

My website uses cookies to enhance your browsing experience. Cookies help us understand how you use our website and allow me to offer personalized content or services. You can control or disable cookies through your browser settings, but please note that some features of our website may not function properly if cookies are disabled.

4. Data Security

I implement a variety of security measures to safeguard your personal and project-related information. While I strive to use commercially acceptable means to protect your data, no method of transmission over the internet is 100% secure. Therefore, we cannot guarantee its absolute security but work diligently to prevent unauthorized access.

5. Third-Party Services

I may use third-party tools or services to improve our website or deliver our services. These third parties may collect information about your interaction with my website. However, I ensure that any third-party services we use adhere to strict privacy and security standards.

6. Your Rights

You have the right to:

  • Request access to any personal information I hold about you.
  • Request corrections or updates to your personal information.
  • Request the deletion of your personal information from my records, subject to legal requirements.
  • Opt out of receiving marketing communications from me at any time.

To exercise these rights, please contact me using the information provided below.

7. Changes to the Privacy Policy

I may update this Privacy Policy from time to time to reflect changes in our practices or legal obligations. The updated policy will be posted on this page, and the effective date will be revised accordingly.

8. Contact Us

If you have any questions or concerns regarding this Privacy Policy or how we handle your data, please contact us at:

  • Email: me@mossawir.com
  • Phone: +92 333 2080504

By using my website and services, you agree to the terms of this Privacy Policy.

I take client confidentiality very seriously and am committed to maintaining the privacy and security of all information shared during our project. Below are the key principles I adhere to:

  1. Confidential Information
    Any information you provide, including business details, design specifications, proprietary data, or any other sensitive material, will be treated as strictly confidential.

  2. Non-Disclosure
    I will not disclose, share, or use any confidential information for any purpose outside the scope of your project. Information shared will be used solely for the purpose of delivering the services you've hired me for.

  3. Data Security
    All files, assets, and credentials will be stored securely, ensuring that no unauthorized third parties can access your information. Upon project completion, sensitive data will be properly stored or destroyed, as per our agreement.

  4. Third-Party Involvement
    If third-party collaboration is required, I will ensure that any partners or subcontractors adhere to the same confidentiality standards.

  5. Ownership of Work
    All project-related files, code, and design materials developed during the project remain your intellectual property, and no elements will be reused or shared without your consent.

  6. Post-Project Confidentiality
    Even after the project is completed, all confidential information shared will continue to be protected.