How do you toggle showing and hiding a div element using JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you toggle showing and hiding a div element using JavaScript?

message-square
0

To toggle showing and hiding an HTML <div> element in JavaScript, toggle a dedicated CSS class (such as .is-hidden with display: none) via element.classList.toggle(...) or read and update element.style.display directly. Toggling a CSS class is generally cleaner than mutating inline style.display because it keeps presentation rules in CSS, preserves your element’s intended display mode (block, flex, grid, or inline-block), and avoids leaving inline styles behind.


1. Toggling a CSS .is-hidden Class with element.classList.toggle()

Define a CSS rule (for example, .is-hidden { display: none; }) and use element.classList.toggle("is-hidden")—or pass a boolean force argument (toggle("is-hidden", shouldHide)) when syncing visibility explicitly with application state:

// Toggle visibility using a CSS class and return whether the element is now visible
function toggleDivVisibility(divElement, forceHidden) {
  if (!(divElement instanceof HTMLElement)) {
    throw new TypeError("Expected a valid HTMLElement.");
  }

  const isNowHidden =
    typeof forceHidden === "boolean"
      ? divElement.classList.toggle("is-hidden", forceHidden)
      : divElement.classList.toggle("is-hidden");

  const isVisible = !isNowHidden;
  divElement.setAttribute("aria-hidden", String(!isVisible));
  return isVisible;
}

// Example CSS rule:
// .is-hidden { display: none; }
  • Preserves flex/grid layouts: Unlike setting element.style.display = "block", toggling a CSS class lets a flex or grid container return to display: flex or display: grid when shown again.
  • Explicit state control: Passing true or false as the second argument to .classList.toggle() prevents out-of-sync states when state comes from data or a toggle button.

2. Toggling element.style.display Directly in JavaScript

If you do not want to rely on a stylesheet class or need quick inline toggling, check the element’s current display state (using getComputedStyle(divElement).display so stylesheet rules are respected on the very first click) and switch between "none" and the element’s restored display value:

// Toggle display: none vs. a remembered display mode using inline styles
function toggleDisplayInline(divElement, visibleDisplay = "block") {
  if (!(divElement instanceof HTMLElement)) {
    throw new TypeError("Expected a valid HTMLElement.");
  }

  const computedDisplay = window.getComputedStyle(divElement).display;
  const currentlyHidden = divElement.style.display === "none" || computedDisplay === "none";

  if (currentlyHidden) {
    const restoredDisplay =
      divElement.dataset.previousDisplay && divElement.dataset.previousDisplay !== "none"
        ? divElement.dataset.previousDisplay
        : visibleDisplay;

    divElement.style.display = restoredDisplay;
    return true;
  }

  if (computedDisplay !== "none") {
    divElement.dataset.previousDisplay = computedDisplay;
  }

  divElement.style.display = "none";
  return false;
}
  • Use getComputedStyle on first toggle: Reading divElement.style.display alone is "" until set inline, which can trip up naive element.style.display === "none" checks.
  • Keep hidden / aria-expanded in sync: Pair visual hiding with hidden or ARIA attributes on controls when building accessible panels or drawers.

3. Wiring a Toggle Button to a Target <div>

Connect a <button> click handler cleanly with input validation and state updates so clicking repeatedly alternates visibility predictably and never throws if a DOM element is missing:

// Bind a button click to toggle a target <div> element
function bindToggleButton(buttonSelector, panelSelector) {
  const button = document.querySelector(buttonSelector);
  const panel = document.querySelector(panelSelector);

  if (!(button instanceof HTMLElement) || !(panel instanceof HTMLElement)) {
    return null;
  }

  const syncButtonLabel = (isVisible) => {
    button.setAttribute("aria-expanded", String(isVisible));
    button.textContent = isVisible ? "Hide details" : "Show details";
  };

  const initialVisible = !panel.classList.contains("is-hidden");
  syncButtonLabel(initialVisible);

  const handleClick = () => {
    const isVisible = toggleDivVisibility(panel);
    syncButtonLabel(isVisible);
  };

  button.addEventListener("click", handleClick);

  return () => {
    button.removeEventListener("click", handleClick);
  };
}
  • Return a cleanup function: Returning a teardown callback makes it easy to remove listeners in dynamic views or tests.
  • Null-safe DOM lookup: Guarding querySelector() results prevents runtime errors if a selector is absent on a page.

TL;DR: Toggle a CSS class like .is-hidden { display: none; } via divElement.classList.toggle("is-hidden") for clean styling and layout preservation, or inspect getComputedStyle(divElement).display and switch divElement.style.display between "none" and its active display mode.