-
Notifications
You must be signed in to change notification settings - Fork 121
04: Adding the Analogue Clock
Add the following HTML to the file to add a clock face and hands. Place this where prompted inside the div#contentLeft where the comment appears.
<div id="clockFace">
<div id="secondHand"></div>
<div id="minHand"></div>
<div id="hrHand"></div>
<div id="pin"></div>
</div>Assign the DOM elements that make up the clock to const values:
const secondHand = document.getElementById("secondHand");
const minHand = document.getElementById("minHand");
const hrHand = document.getElementById("hrHand");Tip
Add the above to the other const declarations to keep your code clean.
Inline styles can be added directly to HTML elements using the Javascript style property for example:
hrHand.style.backgroundColor = '#0f0';We can use CSS3 transformations to manipulate the HTML above to rotate the clock hands as appropriate. The CSS property transform takes a value in degrees as folllows:
<div id="secondHand" style="transform: rotate(12deg);"></div>Our logic will need to calculate what degree value to apply to this inline style.
We can acquire the hours, minutes and seconds from the date object using its methods of getHours(), getMinutes() and getSeconds();
The returned values will require some maths to convert seconds, minutes and hours into degrees for the rotations.
All three clocks hands are initially lying at 90 degrees to the centre of the clock.
To set seconds we would therefore use:
const seconds = myDate.getSeconds();
const rotSeconds = seconds * 6 - 90;To apply this rotation to the div#secondHand we would use:
secondHand.style.transform = `rotate(${rotSeconds}deg)`;Extend the updateTime function to hold this new logic.
const updateTime = () => {
console.info("tick tock");
const myDate = new Date();
myNode.innerHTML = myDate.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit" });
// analogue clock
const seconds = myDate.getSeconds();
const rotSeconds = seconds * 6 - 90;
secondHand.style.transform = `rotate(${rotSeconds}deg)`;
};Can you complete the task with hour and minute hands? Can you make the hour hand 'creep' between to represent how near it is to the next hour?