As I continue on my journey of learning JavaScript, I challenge myself by building small projects.
Today, I managed to create a digital clock, with a little help from a tutorial.
There are two specific things that I am struggling to grasp, which were not explained in the tutorial. In case anyone is interested, you can find the tutorial here.
Here's the JavaScript code:
setInterval(function() {
let hours = document.querySelector('.hours');
let minutes = document.querySelector('.minutes');
let seconds = document.querySelector('.seconds');
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
hours.innerHTML = h < 10 ? '0' + h : h;
minutes.innerHTML = m < 10 ? '0' + m : m;
seconds.innerHTML = s < 10 ? '0' + s : s;
}, 1000);
Issue #1:
I'm unsure about the usage of new Date()
. As a beginner exploring objects, I attempted using just getHours()
, but it didn't yield the expected result. What am I missing?
Issue #2:
Following the tutorial, if the time was below 10 for hours, minutes, or seconds, they appeared as single digits instead of padded with a zero. I tried implementing some logic like this:
if(m < 10) {
'0' + s
}
Additionally, I experimented with:
if(m < 10) {
s = '0' + s;
return s;
}
However, my attempts were unsuccessful. After reading through the comments, I found a shorthand solution to prepend zeros when necessary, but I am confused about the syntax used, particularly the inclusion of :h
, :m
, and :s
at the end of each statement.
Here's the snippet:
setInterval(function() {
let hours = document.querySelector('.hours');
let minutes = document.querySelector('.minutes');
let seconds = document.querySelector('.seconds');
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
hours.innerHTML = h < 10 ? '0' + h : h;
minutes.innerHTML = m < 10 ? '0' + m : m;
seconds.innerHTML = s < 10 ? '0' + s : s;
}, 1000);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: black;
}
.container {
width: 90vw;
margin: auto;
border: 1px solid rgb(50,50,50);
margin-top: 50vh;
transform: translateY(-50%);
display: flex;
justify-content: space-around;
padding: .5em;
font-size: 3em;
font-family: verdana;
background: rgb(170,190,170);
box-shadow: 0 0 10px black inset;
box-reflect: below 0 linear-gradient(transparent, white);
-webkit-box-reflect: below 0 linear-gradient(transparent, rgba(255,255,255,.5));
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0>
<link rel="stylesheet" href="style.css>
<title>Digital Clock>
</head>
<body>
<div class="container>
<div class="hours></div>
<div class="minutes></div>
<div class="seconds></div>
</div>
<script src="main.js></script>
</body>
</html>