Skip to content

Instantly share code, notes, and snippets.

@MichaelNahum
Created January 16, 2017 17:10
Show Gist options
  • Save MichaelNahum/acb904fed4902ca2a6e2b128693ed206 to your computer and use it in GitHub Desktop.
Save MichaelNahum/acb904fed4902ca2a6e2b128693ed206 to your computer and use it in GitHub Desktop.
JS 30 Day Challenge
CSS + JS Clock Notes:
In order to get two lines to pivot off of the end of each other's x-axis (i.e. the second/minute/hour hands of a clock),
give each instance of the .hand class the attribute "transform-origin: 100%;"
Problem: div's go left-to-right, so the clock won't start at 90 degrees.
Solution: give .hand an attribute of "transform: rotate(90deg);"
Question: How to mimic a mechanical clock's tick-and-stop motion?
Answer: give .hand an attribute of "transition-timing-function: cubic-bezier(0.1, 2.7, 0.58, 1);
The parameters for the cubic-bezier are selected by clicking the icon and pulling the bottom purple button all the way up.
Lastly: to make the "ticks" near-instantaneous, give .hand an attribute of "transition: all 0.05s;"
Lines 3-13 provide the logic for _how_ the hands move. From here on, the code regulates _when_ they move.
Within <script> tags, first select the secondHand element, then pass it into a function which determines its placement:
1) const secondHand = document.querySelector('.second-hand');
2) function setDate() {
const now = new Date(); //creates new Date object
const seconds = now.getSeconds(); //gets current second from Date object
const secondsDegrees = ((seconds / 60) * 360) + 90; //calculates the angle the second hand should hold (and corrects for line 6)
secondHand.style.transform = `rotate(${secondsDegrees}deg)` //rotates the second hand.
}
Repeat for minutes and hours. Write both of these above setDate()
const minsHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');
Now within setDate() function, add the following blocks:
const minutes = now.getMinutes();
minuteDegrees = ((minutes/60) * 360) + 90;
minsHand.style.transform = `rotate(${minuteDegrees}deg)`
const hours = now.getHour();
hourDegrees = ((hours/12) * 360) + 90;
hourHand.style.transform = `rotate(${hourDegrees}deg)`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment