Skip to content

collapse on mobile and open on desktop/tablets feature #65

Open
@Hari-Bonda

Description

@Hari-Bonda

Hey! I wish it had a collapse on mobile and open on desktop/tablets feature. consider adding that in the future ♥
thanks

/**
 * SimpleTOC load function.
 */
const simpletocLoad = function () {
  const buttons = document.querySelectorAll("button.simpletoc-collapsible");
  const isDesktop = window.innerWidth >= 768;

  buttons.forEach((button) => {
    const content = button.parentElement.nextElementSibling;

    // On first load, open if desktop
    if (isDesktop) {
      button.classList.add("active");
      button.setAttribute("aria-expanded", "true");
      content.style.maxHeight = `${content.scrollHeight}px`;
    } else {
      button.setAttribute("aria-expanded", "false");
      content.style.maxHeight = "0px";
    }

    // Toggle on click
    button.addEventListener("click", () => {
      button.classList.toggle("active");
      const isCollapsed =
        !content.style.maxHeight || content.style.maxHeight === "0px";

      button.setAttribute("aria-expanded", isCollapsed ? "true" : "false");
      content.style.maxHeight = isCollapsed
        ? `${content.scrollHeight}px`
        : "0px";
    });
  });
};

// Allow others to call function if needed.
window.simpletocLoad = simpletocLoad;

// Run when DOM is ready
if (document.readyState === "complete" || document.readyState !== "loading") {
  simpletocLoad();
} else {
  document.addEventListener("DOMContentLoaded", simpletocLoad);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions