You can show or hide a running JavaScript clock with a normal button and native DOM APIs. jQuery is not required for this simple interaction.
The clock display is one element. The button changes its hidden state, while a timer updates the text whenever it is visible.
let visible = true;
button.addEventListener("click", () => {
visible = !visible;
clock.hidden = !visible;
button.setAttribute("aria-expanded", String(visible));
});
const formatter = new Intl.DateTimeFormat(undefined, { timeStyle: "medium" });
const update = () => {
clock.textContent = formatter.format(new Date());
};
setInterval(update, 1000);
No. The original version of this tutorial used jQuery's toggle(), but current browsers provide everything required through addEventListener() and the hidden property. If an existing project already depends on jQuery, using it is still possible, but it is unnecessary for this task.
Use a real <button>, connect it to the controlled region with aria-controls, and keep aria-expanded synchronized with visibility. Avoid making a non-interactive element such as a <span> behave like a button.
onclick when the behavior can be attached cleanly with JavaScript.Real-Time Clock Date Reference
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.