Introduction
Creating a stopwatch is a great way for beginners to learn HTML, CSS, and JavaScript. In this article, you'll build a fully functional stopwatch with features like lap recording, a theme switcher, and a responsive design. This project will teach you how to work with JavaScript time events, manipulate the DOM, and improve your web design skills. Whether you're just starting out or looking to practice your coding skills, this article will help you create a useful and interactive stopwatch.
What You’ll Need
- Basic knowledge of HTML, CSS, and JavaScript.
- A text editor (like VS Code).
- A browser (e.g., Chrome).
Step 1. Create the Basic HTML Structure.
Start with the HTML structure. The enhancements include.
- A time display.
- Buttons for Start, Stop, and Reset.
- A Lap button to record time intervals.
- A list to show recorded Lap times.
- A theme toggle switch.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enhanced Stopwatch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="stopwatch">
<h1>Stopwatch</h1>
<div id="display">00:00:00</div>
<div class="buttons">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<button id="lap">Lap</button>
</div>
<ul id="laps"></ul>
<div class="theme-toggle">
<label for="theme">Toggle Theme</label>
<input type="checkbox" id="theme">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2. Style the Stopwatch with CSS
We’ll style the stopwatch, add lap display formatting, and implement a responsive design.
CSS Code
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: var(--bg-color, #f0f0f0);
transition: background-color 0.3s ease;
}
.stopwatch {
text-align: center;
background: var(--box-color, #fff);
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
#display {
font-size: 2rem;
margin: 20px 0;
}
.buttons button {
margin: 5px;
padding: 10px 20px;
font-size: 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
}
#start { background: #28a745; color: #fff; }
#stop { background: #dc3545; color: #fff; }
#reset { background: #ffc107; color: #fff; }
#lap { background: #007bff; color: #fff; }
ul#laps {
list-style-type: none;
padding: 0;
max-height: 100px;
overflow-y: auto;
}
ul#laps li {
padding: 5px;
border-bottom: 1px solid #ddd;
}
.theme-toggle {
margin-top: 15px;
}
@media (max-width: 600px) {
.stopwatch {
width: 90%;
}
}
Step 3. Add JavaScript for Functionality and Enhancements.
We’ll implement it.
- Stopwatch functions: Start, Stop, Reset.
- Lap recording.
- Theme switching.
JavaScript Code
let startTime, elapsedTime = 0, timerInterval;
const display = document.getElementById("display");
const laps = document.getElementById("laps");
// Format time as HH:mm:ss
function formatTime(ms) {
const date = new Date(ms);
return date.toISOString().substr(11, 8);
}
// Update the display with the elapsed time
function updateDisplay() {
display.textContent = formatTime(elapsedTime);
}
// Start the stopwatch
document.getElementById("start").addEventListener("click", () => {
if (!timerInterval) { // Prevent multiple intervals
startTime = Date.now() - elapsedTime;
timerInterval = setInterval(() => {
elapsedTime = Date.now() - startTime;
updateDisplay();
}, 1000);
}
});
// Stop the stopwatch
document.getElementById("stop").addEventListener("click", () => {
clearInterval(timerInterval);
timerInterval = null; // Ensure the interval is cleared
});
// Reset the stopwatch
document.getElementById("reset").addEventListener("click", () => {
clearInterval(timerInterval);
timerInterval = null; // Clear any running interval
elapsedTime = 0; // Reset elapsed time
updateDisplay(); // Reset the display
laps.innerHTML = ""; // Clear lap times
});
// Record a lap
document.getElementById("lap").addEventListener("click", () => {
if (timerInterval) { // Only record laps if the stopwatch is running
const lapItem = document.createElement("li");
// Add lap time
lapItem.textContent = `Lap ${laps.children.length + 1}: ${formatTime(elapsedTime)}`;
// Create a delete button for each lap
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.style.marginLeft = "10px";
deleteBtn.style.cursor = "pointer";
// Add delete functionality
deleteBtn.addEventListener("click", () => {
lapItem.remove(); // Remove this lap from the list
});
// Append the delete button to the lap item
lapItem.appendChild(deleteBtn);
laps.appendChild(lapItem);
}
});
// Toggle theme
document.getElementById("theme").addEventListener("change", (e) => {
if (e.target.checked) {
document.documentElement.style.setProperty("--bg-color", "#1e1e1e");
document.documentElement.style.setProperty("--box-color", "#333");
document.documentElement.style.setProperty("color", "#fff");
} else {
document.documentElement.style.removeProperty("--bg-color");
document.documentElement.style.removeProperty("--box-color");
document.documentElement.style.removeProperty("color");
}
});
Here’s a simple breakdown of how the code works.
- Buttons Control the Stopwatch: There are four buttons—Start, Stop, Reset, and Lap. Each button controls a different function of the stopwatch.
- JavaScript Updates the Page: When you interact with the stopwatch, JavaScript changes what's displayed on the page. It shows the time that's passed, records lap times, and updates the theme (like switching between dark and light mode).
- Event Listeners: These buttons have "event listeners" attached to them. This means when you click a button, a specific action happens.
- Start begins the stopwatch.
- Stop pausing it.
- Reset resets everything back to zero.
- Lap records the current time as a lap.
- Dynamic Changes: Every time you press a button, the page updates to show the current state, like showing the elapsed time, adding lap times, or changing the theme.
So, this allows you to interact with the stopwatch and see things update in real-time on your screen.
How It Works Now
- Each lap entry includes a "Delete" button.
- Clicking the Delete button removes only that specific lap from the list.
Output
Conclusion
In this article, we’ve built a simple yet functional stopwatch using HTML, CSS, and JavaScript. You’ve learned how to create interactive features such as lap recording, theme switching, and responsive design. This project not only improves your skills in working with time events and manipulating the DOM, but it also gives you hands-on experience in designing a user-friendly interface. By the end of this article, you’ve created a useful tool that you can expand further as you continue to develop your coding abilities.
Happy coding!