If you've ever wanted an accordion-like user interface without all the fuss of custom JavaScript, CSS, and HTML look no further than the <detail>
and <summary>
tags in HTML5.
The HTML Details Element (<details>
) creates a container element that is only visible when toggled into an "open" state. A summary can be optionally provided using the <summary>
element.
When combined the <details>
and <summary>
elements give you a primitive toggle list of content with HTML alone. I like using this pattern for frequently asked questions, support documentation, or other documentation alone. It's very handy and fast to get started with.
For this tutorial, I made a custom CodePen to demonstrate how it works.
The typical markup looks like the following:
<details>
<summary><strong>summary</strong> text</summary>
Lorem ipsum dolor sit amet consectetur, adipisici......
</details>
The <details>
tags surround both the content and the <summary>
tags by design. The content within the <details>
tags remains hidden minus the <summary>
tags contents which acts as a toggle/control for expanding the hidden content.
Showing a <details>
block by default
You can open a <details>
element by default by passing open
as an attribute.
<details open>
<summary><strong>summary</strong> text</summary>
Lorem ipsum dolor sit amet consectetur, adipisici......
</details>
Leveraging JavaScript with details and summary
On top of the built-in toggling effect, you can add additional styles using a "toggle" event listener built into the browser.
Here's a quick example of what you could achieve
const detailsElements = document.querySelectorAll('details')
detailsElements.forEach((detail) => {
detail.addEventListener('toggle', () => {
if (detail.open) {
detail.style.borderColor = "red";
} else {
detail.style.borderColor = "#777777";
}
})
})
The code above scans the entire page for <details>
elements. For every element that gets "toggled" we listen for that change and toggle the styles directly. In this case, I change the border color.
Be sure to check the final CodePen for a better example!
Shameless plug!
I have a new free course coming out soon called Hello HTML & CSS. It's a course designed to help you learn HTML & CSS from scratch.
Top comments (0)