點燈坊

失くすものさえない今が強くなるチャンスよ

Using Collapse Plugin for Accordion

Sam Xiao's Avatar 2022-01-13

Accordion is a common effect by toggling the element. We can implement it just by Apline and TailwindCSS without any package.

Version

Alpine 3.9

Collapse

collapse000

<div> is toggled by accordion effect.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script
      defer
      src="https://unpkg.com/@alpinejs/collapse@3.x.x/dist/cdn.min.js"
    ></script>
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine</title>
  </head>
  <body x-data="{ isShow: false }">
    <button @click="isShow = ! isShow">Toggle</button>
    <p x-show="isShow" x-collapse.duration.1000ms>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad atque earum
      illum in omnis quaerat, quos ullam? Ad adipisci eligendi error eum fugiat
      minima, minus molestiae, nemo officiis quo reiciendis.
    </p>
  </body>
</html>

Line 15

<p x-show="isShow" x-collapse.duration.1000ms>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad atque earum illum in omnis quaerat, quos ullam? Ad adipisci eligendi error eum fugiat minima, minus molestiae, nemo officiis quo reiciendis.
</p>
  • isShow : toggle isShow state to show <div>
  • x-collapse.duration.1000ms : collapse <div> by 1000ms duration time

Conclusion

  • We can quickly implement the accordion effect by the Collapse plugin

Reference

Alpine, Collapse Plugin