<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Countdown Clock</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<section class="countdown-clock">
<div class="countdown-clock-controls">
<button value="20">20 secs</button>
<button value="300">Work 5</button>
<button value="900">Quick 15</button>
<button value="1200">Snack 20</button>
<button value="3600">Lunch Break</button>
<input type="text" name="interval" placeholder="Enter minutes">
</div>
<div class="countdown-clock-wrapper">
<div class="clock">00:00</div>
<div class="back-at">Back at</div>
</div>
</section>
<script src="./scripts.js"></script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
align-items: center;
flex-direction: column;
color: #434040;
background: linear-gradient(to top, #96fbc4 0%, #f9f586 100%);
}
.countdown-clock {
height: 100%;
display: flex;
flex-direction: column;
}
.countdown-clock-controls {
width: 750px;
justify-self: flex-start;
display: flex;
justify-content: space-between;
margin-top: 30px;
}
.countdown-clock-controls > * {
padding: 20px;
background: rgba(255, 255, 255, 0.5);
border-radius: 10px;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
outline: none;
border: none;
}
.countdown-clock-controls input {
border: 2px solid transparent;
}
.countdown-clock-controls button:hover { background: rgba(255, 255, 255, 0.8); }
.countdown-clock-controls button:active { transform: scale(1.1); }
.countdown-clock-controls input:focus { border: 2px solid #1e89e4; }
.countdown-clock-wrapper {
margin: auto;
text-align: center;
}
.clock {
font-size: 180px;
}
.back-at {
font-size: 23px;
}
const buttons = document.querySelectorAll('.countdown-clock-controls button'),
enterTime = document.querySelector('.countdown-clock-controls input'),
clock = document.querySelector('.clock'),
backAt = document.querySelector('.back-at');
let timer;
function startTimer(seconds) {
clearInterval(timer);
let now = Date.now(),
then = now + (seconds * 1000);
displayTimeLeft(seconds);
displayBackAt(then);
timer = setInterval(() => {
let secsLeft = Math.round((then - Date.now()) / 1000);
if (secsLeft < 0) {
clearInterval(timer);
return;
}
displayTimeLeft(secsLeft);
}, 1000);
}
function displayTimeLeft(secsLeft) {
let minutes = Math.floor(secsLeft / 60),
secs = secsLeft % 60;
clock.textContent = `${formatTime(minutes)}:${formatTime(secs)}`;
}
function displayBackAt(then) {
let end = new Date(then),
hours = end.getHours(),
minutes = end.getMinutes();
backAt.textContent = `Back at ${formatTime(hours)}:${formatTime(minutes)}`;
}
function formatTime(time) {
return `${time < 10 ? '0' : ''}${time}`;
}
function setSeconds(e) {
let value = parseInt(this.value),
secs = e.type === 'click' ? value : value * 60;
startTimer(secs);
}
buttons.forEach(button => button.addEventListener('click', setSeconds));
enterTime.addEventListener('keyup', setSeconds);