I am coding a digital clock. The seconds in the clock should be hideable witch clicking on button if the user wants this. When I am clicking on the button seconds will be hide but only until the next second is in turn. If the next second is elapsed the users preferences are unintentionally setted to default.
let currentDate = new Date();
//assigning function above to a variable
let formattedDate = displayTime(currentDate);
//new time will be displayed every second
setInterval(() => {
currentDate = new Date();
formattedDate = displayTime(currentDate);
formattedDate;
}, 1000);
function displayTime(dataObject) {
const disDate = document.getElementById("date-elements");
const disTime = document.getElementById("time-elements");
//time-objects
const parts = {
//date elements:
weekday: dataObject.getDay(),
daysNumber: dataObject.getDate(),
month: dataObject.getMonth() + 1,
year: dataObject.getFullYear(),
//time elements:
hours: dataObject.getHours(),
minutes: dataObject.getMinutes(),
seconds: dataObject.getSeconds(),
};
//adding "PM" or "AM" respectively depending on days time
const formatAMPM = parts.hours >= 12 ? "PM" : "AM";
const dayState = formatAMPM;
parts.hours = parts.hours % 12;
parts.hours ? parts.hours : 12;
//appending zero if smaller than 10
const dysNmbr =
parts.daysNumber < 10 ? "0" + parts.daysNumber : parts.daysNumber;
const mnth = parts.month < 10 ? "0" + parts.month : parts.month;
const hrs = parts.hours < 10 ? "0" + parts.hours : parts.hours;
const mins = parts.minutes < 10 ? "0" + parts.minutes : parts.minutes;
const secs = parts.seconds < 10 ? "0" + parts.seconds : parts.seconds;
//array of weekdays names
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
//determine the weekday
const currentDayName = days[parts.weekday];
//displayed elements
disDate.innerHTML = `${currentDayName}, ${dysNmbr}/${mnth}/${parts.year}`;
disTime.innerHTML = `${hrs} : ${mins} : ${secs} ${dayState}`;
//hide and show seconds depending on users preferences
let i = true;
const btn = document.getElementById("btn");
//if button is clicked
btn.addEventListener("click", () => {
if (i) {
//hiding seconds
disTime.innerHTML = `${hrs} : ${mins} ${dayState}`;
btn.innerHTML = "Display Seconds";
i = false;
} else {
//displaying seconds
disTime.innerHTML = `${hrs} : ${mins} : ${secs} ${dayState}`;
btn.innerHTML = "Hide Seconds";
i = true;
}
});
}
<div id="date-elements"></div>
<div id="time-elements"></div>
<button id="btn">Hide seconds</button>