Creating an animated stopwatch is a fun and simple project that can be done with HTML, CSS, and JavaScript. Follow this guide to create your own stopwatch with start, stop, and reset functionality.
Step 1: Setting Up the HTML
First, create the basic HTML structure for the stopwatch. Here’s the HTML setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Animated Stopwatch</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="stopwatch">
<div class="display">00:00:00</div>
<div class="buttons">
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
<button onclick="reset()">Reset</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: Styling with CSS
Next, style the stopwatch to make it visually appealing. Here’s the CSS you need:
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
}
.stopwatch {
background-color: #2a05ff;
border-radius: 50%;
padding: 40px;
position: relative;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.stopwatch:after {
content: '';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 10px;
height: 10px;
background-color: #fff;
border-radius: 50%;
}
.display {
color: #fff;
font-size: 2.5em;
text-align: center;
margin-bottom: 20px;
}
.buttons {
display: flex;
justify-content: center;
}
.buttons button {
background-color: #444;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 20px;
margin: 0 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.buttons button:hover {
background-color: #666;
}
Step 3: Adding Functionality with JavaScript
Finally, add JavaScript to control the stopwatch. This script will manage the start, stop, and reset functions:
let timer;
let time = 0;
function updateTime() {
const hours = Math.floor(time / 3600);
const minutes = Math.floor((time % 3600) / 60);
const seconds = time % 60;
document.querySelector('.display').textContent =
`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
time++;
}
function start() {
clearInterval(timer);
timer = setInterval(updateTime, 1000);
}
function stop() {
clearInterval(timer);
}
function reset() {
clearInterval(timer);
time = 0;
updateTime();
}
With this code, you now have a functional animated stopwatch. You can start, stop, and reset the timer as needed. Feel free to modify the styles and functionality to suit your preferences.
Conclusion
Creating an animated stopwatch is a straightforward project that helps you understand the basics of HTML, CSS, and JavaScript. This guide provides a simple example that you can build upon. Happy coding!
Comments
Post a Comment