Create Your Own Timer with CSS Pie Timer Re-Revisited

27 May 2023 Balmiki Mandal 0 MERN Full Stack

CSS Pie Timer Re-visited - How to Create a Countdown Using CSS and JavaScript

The CSS Pie Timer is a great way to create a countdown timer in HTML, CSS, and JavaScript. In this post, we will be looking at how to build a simple CSS Pie Timer. We'll also dive into some of the best practices for creating a great-looking, reusable animation.

What Is A Pie Timer?

A pie timer is a simple visual representation of a countdown timer. The idea is to have a circle or pie that shrinks in size as the time ticks down. This type of timer is often used to indicate progress, or in our case, a countdown.

Creating the Basic Structure

First, we need to create the HTML structure for our pie timer. We'll also add a few basic classes to style the elements. Here's what we'll be creating:

<div class="pie-timer">
  <div class="pie"></div>
  <div class="seconds"></div>
</div>

Adding Some CSS

Next, let's add some basic styles to our elements. We'll set up the main wrapper to be centered on the page, then add some styles to the inner elements. We'll also add some basic animation to make our pie timer transition smoothly.

.pie-timer {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 400px;
  height: 400px;
}

.pie, .seconds {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transform-origin: 50% 50%;
  transition: all 1s ease;
}

.pie {
  background-color: pink;
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}

.seconds {
  background-color: red;
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}

Making it Functional with JavaScript

Finally, we can add the necessary JavaScript to make our pie timer functional. We'll need to listen for a click event on the wrapper element and then update the clip-path on the inner elements to reflect the remaining time. Here's the basic JavaScript code for our pie timer:

const timer = document.querySelector('.pie-timer');

timer.addEventListener('click', () => {
  // Calculate remaining time
  let totalTime = 10; // 10 seconds
  let currentTime = Date.now();
  let timeLeft = totalTime - (currentTime - startTime) / 1000;

  // Update the clip-path of the inner elements
  let angle = (timeLeft / totalTime) * 360;
  let x = Math.sin(angle * Math.PI / 180) * 100;
  let y = Math.cos(angle * Math.PI / 180) * -100;
  let mid = (angle > 180) ? 1 : 0;
  let path = 'polygon(50% 0%, 0% 100%, ' + mid * 100 + '% 100%, ' + x + '% ' +  y + '%)';

  document.querySelector('.pie').style.clipPath = path;
  document.querySelector('.seconds').style.clipPath = path;
});

And that's it! We now have a working pie timer that we can easily reuse and customize as needed.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.