The Details Element

What it is

Click Me!

The HTML details element creates collapsable content.

It is currently only supported by Chrome, but support can be added to other browsers fairly easily.


How it works

The details element should look something like this...

<details>
<summary>Click Me!</summary>
<p>Whatever content to be collapsed</p>
</details>
It has a boolean attribute open that determines the visibilty of its content. When supported, clicking on <summary> toggles the open attribute on its parent <details>. To add support in other browsers, we will need a tiny amount of JavaScript and some CSS.

The JavaScript

document.querySelector('details > summary').addEventListener('click',function(){
(this.parentElement.hasAttribute('open')) ? this.parentElement.removeAttribute('open') : this.parentElement.setAttribute('open', '');
});

The CSS

details[open] > summary::before {
    font-family: 'Web Symbols';
    content: '['
}
details:not([open]) > summary::before { font-family: 'Web Symbols'; content: ']' }
details:not([open]) > :not(summary) { display: none; }
This CSS is specific to my icon-font, Web Symbols, which I use (obviously) for many of my icons. To make it work with another font, just replace the font-family with your icon-font of choice and replace the content with whichever character is appropriate. It could also be done with the CSS triangles hack for better support and without relying on an icon.

Support

Support for this method is pretty good. You need querySelector support, CSS negation and attribute selectors, and generated content support.

Note: IE8 requires only a single ':' in before rather than double. Either will work for other browsers, but the double colon is actually correct.