Build Your Own Stopwatch: HTML, CSS, and JavaScript Tutorial

Faraz

By Faraz -

Discover the world of web development by creating a beautiful stopwatch UI. Learn HTML, CSS, and JavaScript while building a practical timekeeping tool.


Build Your Own Stopwatch HTML, CSS, and JavaScript Tutorial.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Welcome to a fascinating journey into the world of web development, where you'll learn how to create a functional and visually appealing stopwatch using the power of HTML, CSS, and JavaScript. In today's digital age, timekeeping tools are more essential than ever, and this tutorial will empower you to craft your very own stopwatch while honing your web development skills.

Whether you're a novice looking to embark on your coding adventure or an experienced developer seeking to add a practical project to your portfolio, this step-by-step guide has something for everyone. By the end of this tutorial, you'll not only have a fully operational stopwatch but also a deeper understanding of how HTML, CSS, and JavaScript work together to create dynamic user interfaces.

So, roll up your sleeves, fire up your code editor, and let's dive into the art of crafting a stylish and functional stopwatch for your web applications.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our stopwatch.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

1. <!DOCTYPE html>: This declaration specifies that the document is written in HTML5, the latest version of HTML.

2. <html lang="en">: This is the opening tag of the HTML document. It defines the root element of the document and specifies that the document's primary language is English ("en").

3. <head>: This is the head section of the HTML document. It contains meta-information about the document and links to external resources.

  • <meta charset="UTF-8">: This meta tag specifies that the character encoding used in the document is UTF-8, which supports a wide range of characters and is commonly used for web content.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is used to set the compatibility mode for Internet Explorer. It ensures that the document will be displayed in the latest available rendering engine.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is used for responsive web design. It sets the viewport width to the device's width and initial zoom level to 1.0, ensuring proper scaling on different devices.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">: This line links to an external CSS stylesheet from a content delivery network (CDN). It's used to include Font Awesome icons in the document.
  • <link rel="stylesheet" href="styles.css">: This line links to an external CSS file named "styles.css" in the same directory as the HTML file. It's used to apply custom styles to the document.
  • <title>Stopwatch</title>: This sets the title of the web page, which is displayed in the browser's title bar or tab.

4. <body>: This is the body section of the HTML document, where the visible content of the webpage is placed.

5. <h1><i class="fa-solid fa-stopwatch"></i> Stopwatch</h1>: This line creates a heading (h1) element with an embedded Font Awesome icon (the stopwatch icon) and the text "Stopwatch."

6. <div class="container">: This div serves as a container for the main content of the webpage.

7. <div class="time">: This div is used to display the current time in the format "00:00:00."

8. <div class="controls">: This div contains a set of buttons for controlling the stopwatch.

  • <button id="start">Start</button>: A button with the id "start" that is used to start the stopwatch.
  • <button id="lap">Lap</button>: A button with the id "lap" for recording lap times.
  • <button id="stop">Stop</button>: A button with the id "stop" for stopping the stopwatch.
  • <button id="reset">Reset</button>: A button with the id "reset" for resetting the stopwatch.

9. <div class="lapping">: This div is used to display recorded lap times.

  • <h4 id="lap1"></h4>, <h4 id="lap2"></h4>, ...: These are empty h4 elements with unique ids (lap1, lap2, lap3, etc.) for displaying lap times. They appear to be initially empty and will be populated with lap time data via JavaScript.

10. <footer><p>Made with ❤ by Debadrita</p></footer>: This is the footer of the webpage, containing a message that says "Made with ❤ by Debadrita."

11. <script src="script.js"></script>: This line includes an external JavaScript file named "script.js." This script is used to add functionality to the stopwatch, such as starting, stopping, and resetting it, as well as recording lap times.

This is the basic structure of our stopwatch using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the stopwatch is in place, the next step is to add styling to the stopwatch using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our stopwatch. Here's an explanation of each part:

1. @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300&display=swap');: This line imports the Montserrat font with a weight of 300 from Google Fonts. This font will be used for text elements on the web page.

2. * { ... }: This block applies styles to all elements on the page. It sets the box-sizing property to "border-box," which ensures that an element's padding and border are included in its total width and height. It also sets the margin and padding of all elements to 0, effectively removing any default spacing.

3. body { ... }: Styles for the entire webpage's body. It sets the font-family to Montserrat and defines a background color of "#082032" (a dark blue) and text color to "whitesmoke."

4. h1 { ... }: Styles for the level 1 headings (typically used for page titles). It adds a top margin, user-select property set to "none" (preventing text selection), and potentially adjusts the font size on smaller screens.

5. footer { ... }: Styles for the footer section of the page. It sets text alignment to the center and prevents text selection.

6. .container { ... }: Styles for an element with the class "container." This is typically used to wrap a central content area on the page. It gives it a dark background color, centers its contents both vertically and horizontally, and sets a maximum width of 400 pixels. It also adds some margin, padding, and rounded corners.

7. .time { ... }: Styles for elements with the class "time." It sets a large font size and a bottom margin.

8. .controls button { ... }: Styles for buttons within an element with the class "controls." It sets a background color, margin, padding, font size, border radius, and other properties. On hover, it changes the background color and text color for a visual effect.

9. @media(max-width:480px) { ... }: This is a media query that applies styles only when the screen width is 480 pixels or less. Within this query, there are specific styles for elements like h1, .container, .time, and .controls button. These styles are adjusted to make the page more responsive and user-friendly on smaller screens, such as mobile devices.

This will give our stopwatch an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300&display=swap');

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

body {
    font-family: 'Montserrat', sans-serif;
    background: #082032;
    color: whitesmoke;
}

h1 {
    margin: 10px 0 0 20px;
    user-select: none;
}

footer {
    text-align: center;
    user-select: none;
}

.container {
    background: #334756;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    width: 100%;
    max-width: 400px;
    margin: 150px auto;
    padding: 25px;
    border-radius: 5px;
}

.time {
    font-size: 5rem;
    margin-bottom: 10px;
    user-select: none;
}

.controls button {
    background-color: #FF4C29;
    margin: 10px 5px;
    padding: 10px 20px 10px 20px;
    font-size: 1rem;
    border-radius: 4px;
    border: none;
    transition: 0.8s;
    cursor: pointer;
}

.controls button:hover {
    background-color: transparent;
    color: whitesmoke;
}

@media(max-width:480px) {
    h1 {
        font-size: 1.2rem;
    }
    .container {
        max-width: 200px;
    }
    .time {
        font-size: 2rem;
    }
    .controls button {
        padding: 5px;
        margin: 0.5px;
    }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let's break down the code step by step:

1. It starts by selecting several elements from the HTML document using their IDs or class names:

  • time_ele: Represents an element with the class name "time." This is presumably where the stopwatch time will be displayed.
  • start_btn, lap_btn, stop_btn, reset_btn: These variables store references to HTML buttons with the respective IDs "start," "lap," "stop," and "reset."
  • l1, l2, l3, l4, l5: These variables store references to elements with IDs "lap1," "lap2," "lap3," "lap4," and "lap5," which are used to display lap times.

2. It initializes some variables:

  • seconds: Represents the number of seconds that have elapsed on the stopwatch. It starts at 0.
  • interval: Stores the interval ID returned by setInterval, which is used to update the timer display regularly.
  • ctr: Counts the number of lap times recorded.

3. Event listeners are added to the buttons:

  • When the "start" button is clicked, the start function is called.
  • When the "lap" button is clicked, the lap function is called.
  • When the "stop" button is clicked, the stop function is called.
  • When the "reset" button is clicked, the reset function is called.

4. The timer function is defined. This function is called repeatedly using setInterval. It increments the seconds variable and calculates hours, minutes, and seconds from it. Then, it updates the content of the time_ele element to display the formatted time.

5. The start function checks if there's already an interval running. If not, it sets an interval to call the timer function every second.

6. The lap function is called when the "lap" button is clicked. It increments the lap counter ctr and updates the content of the lap time elements (l1, l2, etc.) with the current lap time and lap number based on the value of ctr. It records up to 5 lap times.

7. The stop function clears the interval set by setInterval, effectively pausing the stopwatch.

8. The reset function stops the stopwatch, resets the seconds variable to 0, sets ctr to 0, and updates the time_ele to display "00:00:00."

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

var time_ele = document.getElementsByClassName("time")[0];
var start_btn = document.getElementById("start");
var lap_btn = document.getElementById("lap");
var stop_btn = document.getElementById("stop");
var reset_btn = document.getElementById("reset");
var l1 = document.getElementById("lap1");
var l2 = document.getElementById("lap2");
var l3 = document.getElementById("lap3");
var l4 = document.getElementById("lap4");
var l5 = document.getElementById("lap5");

let seconds = 0;
let interval = null;
let ctr=0;

start_btn.addEventListener("click", start);
lap_btn.addEventListener("click", lap);
stop_btn.addEventListener("click", stop);
reset_btn.addEventListener("click", reset);


function timer() {
    seconds++;


    let hrs = Math.floor(seconds / 3600);
    let mins = Math.floor((seconds - (hrs * 3600)) / 60);
    let sec = seconds % 60;

    if(sec < 10)
        sec = '0' + sec;
    
    if(mins < 10)
        mins = '0' + mins;
    
    if(hrs < 10)
        hrs = '0' + hrs;

    time_ele.innerHTML = `${hrs}:${mins}:${sec}`;
}

function start() {
    if(interval)
    {
        return;
    }

    interval = setInterval(timer, 1000);
}

function lap() {
    ctr++;
    if(ctr%5==1)
        l1.innerHTML="Lap "+ ctr+ ":  " + time_ele.innerHTML;
    if (ctr%5==2)
        l2.innerHTML="Lap "+ ctr+ ":  " + time_ele.innerHTML;
    if (ctr%5==3)
        l3.innerHTML="Lap "+ ctr+ ":  " + time_ele.innerHTML;
    if (ctr%5==4)
        l4.innerHTML="Lap "+ ctr+ ":  " + time_ele.innerHTML;
    if (ctr%5==0)
        l5.innerHTML="Lap "+ ctr+ ":  " + time_ele.innerHTML;

}

function stop() {
    clearInterval(interval);
    interval = null;
}

function reset() {
    stop();
    seconds = 0;
    ctr=0;
    time_ele.innerHTML = "00:00:00";
}

Final Output:

Build Your Own Stopwatch HTML, CSS, and JavaScript Tutorial.gif

Conclusion:

Congratulations on reaching the finish line of this web development journey! You've just learned how to create a sleek and functional stopwatch from scratch using HTML, CSS, and JavaScript. This accomplishment is not just about building a timekeeping tool; it's about equipping yourself with valuable skills that can be applied to countless other web projects.

We hope you enjoyed creating your stopwatch and that it serves as a source of inspiration for your future endeavors in the exciting world of web development. Thank you for joining us on this educational adventure, and may your coding adventures be filled with success and creativity!

Stay curious, keep coding, and remember: the web is your canvas, and you're the artist.

Made by: Debadrita

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post