Toggle a JavaScript Clock with a Button

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.

How the Clock Toggle Demo Works Top ↑

The clock display is one element. The button changes its hidden state, while a timer updates the text whenever it is visible.

Toggle Visibility with the hidden Property Top ↑

let visible = true;
button.addEventListener("click", () => {
  visible = !visible;
  clock.hidden = !visible;
  button.setAttribute("aria-expanded", String(visible));
});

Keep the Clock Updated Top ↑

const formatter = new Intl.DateTimeFormat(undefined, { timeStyle: "medium" });
const update = () => {
  clock.textContent = formatter.format(new Date());
};
setInterval(update, 1000);

Is jQuery Needed to Toggle a Clock? Top ↑

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.

Accessibility Considerations Top ↑

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.

Common Clock Toggle Mistakes Top ↑

  • Loading a second old jQuery copy just for one toggle.
  • Starting a new clock timer every time the display is shown.
  • Using inline onclick when the behavior can be attached cleanly with JavaScript.
  • Hiding content visually without keeping accessibility state in sync.

Real-Time Clock Date Reference




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer