Posts

Step-by-Step Guide to Adding a Dark Mode Toggle | Easy Tutorial

Step-by-Step Guide to Adding a Dark Mode Toggle | Easy Tutorial
Create Dark Mode Toggle with HTML, CSS, and JavaScript

Create a Dark Mode Toggle with HTML, CSS, and JavaScript

In this blog post, we will learn how to create a simple dark mode toggle button using HTML, CSS, and JavaScript. Dark mode is a popular feature that allows users to switch the theme of the website to a darker color scheme. It’s easy to implement and gives your website a modern look!

Step-by-Step Code:

1. HTML Code

<!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="styles.css">
</head>
<body>
    <div class="container">
        <h1>Dark Mode Toggle Example</h1>
        <button id="toggleButton">Toggle Dark Mode</button>
    </div>

    <script src="script.js"></script>
</body>
</html>
            

2. CSS Code

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    transition: background-color 0.5s ease;
}

.container {
    text-align: center;
}

h1 {
    color: #333;
    transition: color 0.5s ease;
}

button {
    padding: 10px 20px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    background-color: #4CAF50;
    color: white;
    transition: background-color 0.5s ease;
}

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

body.dark-mode h1 {
    color: white;
}

body.dark-mode button {
    background-color: #f1c40f;
    color: black;
}
            

3. JavaScript Code

const toggleButton = document.getElementById('toggleButton');
const body = document.body;

toggleButton.addEventListener('click', () => {
    body.classList.toggle('dark-mode');
});
            

Explanation:

Here’s a breakdown of the code:

  • HTML: The structure includes a button that toggles the dark mode.
  • CSS: Defines both the default light theme and the dark theme using the dark-mode class. Smooth transitions are used for background color and text color changes.
  • JavaScript: A simple script that toggles the dark-mode class when the button is clicked, switching between light and dark modes.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.
NextGen Digital Welcome to WhatsApp chat
Howdy! How can we help you today?
Type here...