I have a clock in my website, and I would like to add a button or switch into settings that switches the time from 12 hour and 24 hour and vice versa.
My problem is that I have no idea where to connect the setClockStyle in the clock.js
const displayTime = document.querySelector(".display-time");
function showTime() {
let time = new Date();
displayTime.innerText = time.toLocaleTimeString("en-US", {
hour12: true,
hour: '2-digit',
minute: '2-digit'
});
setTimeout(showTime, 1000);
}
showTime();
function updateDate() {
let today = new Date();
let dayName = today.getDay(),
dayNum = today.getDate();
const IDCollection = ["daynum"];
const val = [dayNum];
for (let i = 0; i < IDCollection.length; i++) {
document.getElementById(IDCollection[i]).firstChild.nodeValue = val[i];
}
}
updateDate();
And buttons
<div class="section-title">Clock Style</div>
<div class="buttons">
<button class="button" onclick="setClockStyle('12')">12hr</button>
<button class="button" onclick="setClockStyle('24')">24hr</button>
</div>
2
Answers
Use a global variable to hold the flag for 12 or 24-hour time. Then use that in
showTime()
.Then
setClockStyle()
can simply set the variable appropriately:I made 2 snippets the first is without using setClockStyle function (you don’t really need) and then adding argument ‘format’ in your function (will be either true or false for hour12).
The second one with using setClockStyle that will take the argument as true or false and pass it to showtime function.