Skip to content

Instantly share code, notes, and snippets.

@PremshankarTiwari
Last active November 5, 2019 09:03
Show Gist options
  • Save PremshankarTiwari/783baac3f6f3ea09f6d577b36f16ed93 to your computer and use it in GitHub Desktop.
Save PremshankarTiwari/783baac3f6f3ea09f6d577b36f16ed93 to your computer and use it in GitHub Desktop.
Clock snippet (analog and digital) using only HTML, CSS and JS. Demo: https://466659.playcode.io/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Clock Snippet</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="clock">
<hr id="second-hand">
<hr id="minute-hand">
<hr id="hour-hand">
</div>
<div id="time"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
function updateTime(){
let date = new Date();
let hours = date.getHours();
let ampm = "AM";
if(hours > 12){
hours = hours - 12;
ampm = "PM";
}
let minutes = date.getMinutes();
let seconds = date.getSeconds();
let hourPercentage = minutes/60*30;
let hourIncrement = -90 + 360/12 * hours + hourPercentage;
let minIncrement = -90 + 360/60 * minutes;
let secIncrement = -90 + 360/60 * seconds;
hours = ("0"+hours).slice(-2);
minutes = ("0"+minutes).slice(-2);
seconds = ("0"+seconds).slice(-2);
document.getElementById('time').innerHTML = "time: "+hours+ ":" +minutes+ ":" +seconds+" "+ampm;
document.getElementById('hour-hand').style.transform = 'rotate('+hourIncrement+'deg)';
document.getElementById('minute-hand').style.transform = 'rotate('+minIncrement+'deg)';
document.getElementById('second-hand').style.transform = 'rotate('+secIncrement+'deg)';
}
setInterval(updateTime, 1000);
body {
background: #161616;
color: #fff;
font-weight: 300;
margin: 0;
}
#clock{
border: 5px solid brown;
border-radius: 50%;
height: 250px;
width: 250px;
position: relative;
font-weight: bold;
color: #000;
background: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQKn2JBVtM_lODrMvLm444hWeYj9EmTZPDzjM9l3gnCFGEmoqWP&s");
background-repeat: no-repeat;
background-size: 92%;
background-position: 11px;
background-color: #fff;
margin: 20px auto;
}
#time{
font-weight: bold;
font-size: 20px;
font-family: Arial, Helvetica, sans-serif;
text-transform: capitalize;
text-align: center;
}
hr{
width: 50%;
background-color: brown;
font-weight: bold;
position: absolute;
top: 50%;
left: 50%;
margin: 0;
transform-origin: left;
border: 0;
border-radius: 50%;
}
#second-hand{
height: 1px;
transform: rotate(-90deg);
width: 40%;
}
#minute-hand{
height: 3px;
transform: rotate(-90deg);
width: 38%;
}
#hour-hand{
height: 4px;
transform: rotate(-90deg);
width: 30%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment