Introduction: Dark Mode with JavaScript
Dark mode has become a popular feature in many web applications and websites due to its eye-friendly nature and sleek appearance. It helps to reduce eye strain, especially under low light conditions, and can also save battery life on OLED screens. Implementing dark mode in your web application can significantly enhance the user experience. In this article, we will explore how to create a simple dark mode toggle using JavaScript.
Setting Up the HTML and CSS
Firstly, let’s set up the HTML structure and some basic CSS for our web application:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dark Mode Example</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header>
<h1>Embracing the Dark Side: Dark Mode with JavaScript</h1>
</header>
<button id="toggle-button">Toggle Dark Mode</button>
<p>
Dark mode has grown in popularity as it provides a visually soothing
user experience, especially under low-light conditions. It also
tends to save battery life on OLED and AMOLED screens, making it a
desirable feature for modern web applications.
</p>
<script src="script.js"></script>
</body>
</html>
Creating the JavaScript File
Now, create a new file named script.js
and add the following code to toggle the dark mode on and off:
const toggleButton = document.getElementById('toggle-button');
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('dark-mode');
});
Explanation
In the above JavaScript code:
- We first get a reference to the toggle button using
document.getElementById
. - We then set up an event listener on the button for the
click
event. - Inside the event handler, we use
document.body.classList.toggle
to toggle thedark-mode
class on thebody
element.
Adding CSS:
body {
transition: background-color 0.5s ease, color 0.5s ease;
color: #000000; /* Default text color is black */
}
.dark-mode {
background-color: #121212;
color: #ffffff; /* Text color in dark mode is white */
}
h1 {
transition: color 0.5s ease;
}
.dark-mode h1 {
color: #ff5722; /* Example color for heading in dark mode */
}
p {
transition: color 0.5s ease;
}
.dark-mode p {
color: #8bc34a; /* Example color for paragraph text in dark mode */
}
With these simple steps, we have created a basic dark mode toggle for our web application. Now, whenever the user clicks the “Toggle Dark Mode” button, the background color of the page will switch between the default white and dark gray, providing a basic dark mode functionality.
💁 Check out our other articles😃
👉 Generate a free Developer Portfolio website with AI prompts
👉 Build a Simple Calculator App with React, Tailwind CSS. Displays History