Categories
Web development

CSS & jQuery Stopwatch

CSS & jQuery Stopwatch

To learn how to create the CSS & jQuery Stopwatch follow the steps below:

Demo:

*to see the CSS & jQuery Stopwatch on the website click here.

Step1.

Add HTML

<div class="stopwatch"> 
  <div class="screen">
    <div class="time"> 00 : 00 : 00 : 00</div>
  </div>
    <div class="buttons">
    <button class="start">START</button>
    <button class="stop">STOP</button>
    <button class="reset">RESET</button>
    </div>
</div>

Step2.

Add CSS

Set the colour and the position of the background and elements:

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

Style the stopwatch:

.stopwatch {
  position: relative;
  height: 250px;
  width:270px;
  background-color: black;
  border-radius:30px;
  box-shadow: 0 0 30px rgba(0,0,0,0.7);
}

.screen {
  width: 220px;
  height: 80px;
  position: relative;
  background-color: #e9c46a;
  border:5px solid #333;
  border-radius: 20px 20px 0 0;
  top:40px;
  left:20px;
}

.time {
  position: absolute;
  font-size: 30px;
  text-align:center;  
  transform: translateX(-50%) translateY(-50%);
  top:45px;
  left:110px;
  width: 230px;
}


.buttons {
  text-align:center;
  position: relative;
  top:80px;
}

button {
  padding:10px;
}

Step3.

Add jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Tip: Don’t forget to add jQuery library in the <head> section!

$(document).ready(function () {
    var msec;
    var sec;
    var min;
    var hr;
    var interval;
    var count = 0;

$(".start").click(function () {
      $(".start").hide();  
      interval = setInterval(stopWatch, 10); 
    });

function stopWatch() {
      hr = parseInt(count * 10 / 1000 / 60 / 60);
      min = parseInt(count * 10 / 1000 / 60);  
      sec = parseInt((count * 10 / 1000)%60);
      msec = parseInt((count* 10) % 1000/ 10); 

      hr = hr < 10 ? "0" + hr : hr;
      min = min < 10 ? "0" + min : min;
      sec = sec < 10 ? "0" + sec : sec;
      count++; 
      $(".time").text(hr + " : " + min + " : " + sec + " : " + msec);
    }

$(".stop").click(function () {
      $(".start").hide();
      clearInterval(interval);
    });

$(".reset").click(function () {
      $(".time").text("00 : 00 : 00 : 00"); 
      $(".start").show();   
      clearInterval(interval); 
      count = 0;             
    });
  })

Enjoy coding!

Read also:

Countdown Timer

CSS & JavaScript Digital Clock

JavaScript – Time and date