Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>

<head>
  <title>HTML 5 Accordion with GSAP Animation</title>
  <script src="https://kit.fontawesome.com/b15ad03e0d.js" crossorigin="anonymous"></script>
</head>

<body>
  <h1>HTML 5 Accordion Example</h1>
  <div class="accordion">
    <!-- add `exclusive` to require only one item open at all time -->
    <details>
      <summary>Details / Summary <i class="details-icon fa-regular fa-circle-arrow-down"></i></summary>
      <div class="content">This element can display any type of content and may be further stylized with CSS.</div>
    </details>
    <details>
      <summary>GSAP Animation <i class="details-icon fa-regular fa-circle-arrow-down"></i></summary>
      <div class="content">The animation is handled through GSAP. The free version of the plugin should be enough.</div>
    </details>
    <details>
      <summary>Mutation Observer <i class="details-icon fa-regular fa-circle-arrow-down"></i></summary>
      <div class="content">I opted for a Mutation Observer instead of a Pointer Down event in order toggle the elements simply by adding or removing the details <strong>open</strong> attribute.</div>
    </details>
  </div>
</body>

</html>
              
            
!

CSS

              
                $primary: #270374;
$secondary: #bd00ff;
$borders: #e3e3e3;
@import url(https://fonts.googleapis.com/css?family=Noto+Sans);
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  background-color: #efefef;
  font-family: "Noto Sans";
}
h1 {
  margin: 40px;
}
.accordion {
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  width: 350px;
  flex-basis: 350px;
  margin: 40px;
  padding-bottom: 10px;
  border-radius: 20px;
  background-color: white;
  box-shadow: rgba(0, 0, 0, 0.05) 0px 10px 20px,
    rgba(0, 0, 0, 0.1) 0px 10px 10px;
  .titleBar {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 30px 20px;
    .title {
      font-size: 1.4rem;
      font-weight: 600;
      color: $primary;
    }
    button {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      font-size: 0.8rem;
      font-weight: 600;
      border-radius: 50px;
      border: none;
      background-color: $secondary;
      color: white;
      padding: 12px 15px 10px;
      text-decoration: none;
      cursor: pointer;
      width: 105px;
      svg {
        margin-right: 5px;
      }
    }
  }
  details {
    border-top: 1px solid $borders;
    summary {
      list-style: none;
      font-size: 1rem;
      font-weight: 600;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      cursor: pointer;
      color: $primary;
      border-bottom: 1px solid $borders;
      padding: 20px;
      &:last-of-type {
        border-bottom: none;
      }
      svg {
        color: $secondary;
        transform: rotate(90deg);
      }
    }
    .content {
      position: relative;
      font-size: 0.9rem;
      color: #3e3e3e;
      padding: 0 30px 20px 30px;
    }
  }
}

              
            
!

JS

              
                /**
 * Accordion
 * * Takes a details/summary wrapper and adds animation and functionality
 * * wrapper > div.titleBar > .title, button.expand > (details > summary, .content)...
 */
class Accordion {
  constructor(ele) {
    if (ele === null) {
      throw "Initialization failed: A proper wrapper element has not been provided.";
    }
    this.accordionWrapper = ele;
    this.accordions = this.accordionWrapper.querySelectorAll("details");
    this.accordionsArray = gsap.utils.toArray(this.accordions);
    this.expandButton = undefined;
    this.accordionObserver = new MutationObserver(this.accordionMutation);
    this.exclusive = this.accordionWrapper.classList.contains("exclusive");
    this.mutationConfig = {
      attributes: true,
      attributeFilter: ["open"],
      childList: false,
      subtree: false
    };

    this.accordionWrapper.prepend();
    /**
     * * Loop all details tags and set initial values such as opacity and state
     * * Open each menu to get the open and closed heights and save as data attributes
     * * Set a Mutation Observer to look for changes to the open tag
     */
    this.accordions.forEach((accordion) => {
      let content = accordion.querySelector(".content");
      let state = accordion.open;
      let opacity = state ? 1 : 0;
      if (state) {
        gsap.set(accordion.querySelector(".details-icon"), { rotation: 90 });
      } else {
        accordion.open = true;
      }
      accordion.dataset.openHeight = accordion.offsetHeight;
      accordion.dataset.closedHeight = accordion.querySelector(
        "summary"
      ).offsetHeight;

      this.accordionObserver.observe(accordion, this.mutationConfig);
      accordion.open = state;
    });

    this.createTitleBar();

    // If exclusive and has expand button
    if (this.expandButton) {
      if (this.exclusive) {
        this.expandButton.style.display = "none";
        this.expandButton.ariaHidden = true;
      } else {
        this.expandButton.addEventListener("pointerdown", () => {
          this.toggleAll();
        });
      }
    }
  }

  get title() {
    const currentTitle = this.accordionWrapper.querySelector(
      ".titleBar .title"
    );
    if (currentTitle) {
      return currentTitle.textContent;
    } else {
      return "No Title Set";
    }
  }

  set title(value) {
    this.accordionWrapper.querySelector(".titleBar .title").textContent = value;
  }

  isOpen = (item) => item.open === true;
  openedItems = () => this.accordionsArray.filter(this.isOpen);
  allOpened = () => this.openedItems().length === this.accordionsArray.length;

  isClosed = (item) => !this.isOpen(item);
  closedItems = () => this.accordionsArray.filter(this.isClosed);
  allClosed = () => this.closedItems().length === this.accordionsArray.length;

  createButton(classes, icon, text, label) {
    let newButton = document.createElement("button");
    newButton.classList.add(...classes.split(" "));
    newButton.ariaLabel = label;
    let buttonIcon = document.createElement("i");
    buttonIcon.classList.add(...icon.split(" "));
    newButton.append(buttonIcon);
    let buttonText = document.createElement("span");
    buttonText.textContent = buttonText;
    newButton.append(buttonText);

    return newButton;
  }

  createTitleBar() {
    let titleBar = document.createElement("div");
    titleBar.className = "titleBar";
    let title = document.createElement("h2");
    title.className = "title";
    title.textContent = this.title;
    titleBar.append(title);

    if (!this.exclusive) {
      this.expandButton = this.createButton(
        "expand",
        "expand-icon fa-solid fa-circle-arrow-down",
        "Expand",
        "Expand or Collapse All"
      );
      titleBar.append(this.expandButton);
    }

    this.accordionWrapper.prepend(titleBar);
  }

  /**
   * toggleState
   * * Opens or closes all details tags
   * - Tests if all details are open
   * -  true: close the details tag by removing the open attribute
   * -  false: if there is at least one closed details tag, open all
   */
  toggleAll() {
    const allOpen = this.allOpened();
    this.accordions.forEach((accordion) => {
      allOpen ? accordion.removeAttribute("open") : (accordion.open = true);
    });
  }

  /**
   * toggleAccordion
   * * Handles the animation to open or close the details tag
   * - Tests for the open attribute on the details tag
   * -  true: animate the details tag to the open position
   * -  else: animate the details tag to the closed position
   * @param {Object} accordion the details tag to process
   */
  toggleAccordion(accordion) {
    const state = accordion.open;
    const content = gsap.utils.toArray(accordion.childNodes);
    const icon = accordion.querySelector(".details-icon");
    let tl = gsap.timeline({
      defaults: { duration: 0.5, ease: "power4.out" }
    });

    // if state is true (open), open the details tag; else, close the details tag
    if (state) {
      accordion.classList.add("open");
      tl.to(accordion, { height: accordion.dataset.openHeight }, 0)
        .to(
          accordion.querySelector(".content"),
          { opacity: 1, duration: 0.25 },
          0.1
        )
        .to(icon, { rotation: 90 }, 0);

      // If exclusive, close all other details elements
      if (this.exclusive) {
        this.accordions.forEach((ele) => {
          if (ele !== accordion) {
            ele.removeAttribute("open");
            ele.classList.remove("open");
          } else {
            ele.classList.add("open");
          }
        });
      }
    } else {
      accordion.classList.remove("open");
      tl.to(
        accordion.querySelector(".content"),
        { opacity: 0, duration: 0.25 },
        0
      )
        .to(accordion, { height: accordion.dataset.closedHeight }, 0)
        .to(icon, { rotation: 0 }, 0);
    }
  }
  /**
   * accordionMutation
   * * The callback method for a Mutation Observer
   * * If the open tag is added to an accordion details tag, update the toggle button
   * - If the menu is collapsable, test if all details tags are open
   * -  true: update text in expand all button and change icon rotation
   * -  else: set icon to the proper rotation
   * @param {Object} mutationList
   * @param {Object} observer
   */
  accordionMutation = (mutationList, observer) => {
    let btn_tl = gsap.timeline({
      defaults: { duration: 0.5, ease: "power4.out" }
    });
    mutationList.forEach((mutation) => {
      let accordion = mutation.target;

      this.toggleAccordion(accordion);

      if (this.exclusive) {
        accordion.style.pointerEvents = "none";
        this.closedItems().forEach((item) => {
          item.style.pointerEvents = "all";
        });
      } else if (this.expandButton) {
        // Expand Button Logic
        if (this.allOpened()) {
          this.expandButton.querySelector("span").textContent = "Collapse";
          btn_tl.to(
            this.expandButton.querySelector(".expand-icon"),
            { rotation: 180 },
            0
          );
        } else {
          this.expandButton.querySelector("span").textContent = "Expand";
          btn_tl.to(
            this.expandButton.querySelector(".expand-icon"),
            { rotation: 0 },
            0
          );
        }
      } else {
        console.log("no expand button");
      }
    });
  };
}

let accordion = new Accordion(document.querySelector(".accordion"));
accordion.title = "Details/Summary";

              
            
!
999px

Console