Expanding/collapsing with Details

In January 2023 I wrote this item on using the details element to augment alt text on images. I was not aware of another very useful string to the detail's bow until reading this WebAIM article.

Because the WebAIM people have written such a comprehensive article, I won't go into details (there's that word again). Following is a brief example and discussion.

Example: Australian states

ACT

The Australian Capital Territory, consisting of lots of curvy roads and a place where politicians can chat.

NSW

New South Wales, the most populous state, with lots of open space and Sydney, the most congested city in the country.

The code


	<h2>Australian  states</h2>
	<details name="ausStates">
		<summary>
		ACT
		</summary>
		<p>
		The Australian Capital Territory, consisting of lots of curvy roads and a place where politicians can chat.
		</p>
	</details>
	<details name="ausStates">
		<summary>
		NSW
		</summary>
		<p>
		New South Wales, the most populous state, with lots of open space and Sydney, the most congested  city in the country.
		</p>
	</details>

Discussion

It is important to use the name attribute on the details element for the expanding/collapsing to work. While testing suggested that it is only necessary on the first one, I play it safe and put it on all of them (using the same name of course). I did a version with all states and territories, but the above excerpt will suffice here. You will notice that expanding the second item will collapse the first if it is open. So easy for web authors to write and so nice for readers.

Screen reader and browser support

So far I have not found a screen reader that has any issues. The ESR version of Firefox does not collapse an item when another is expanded. Otherwise, I have found no issues.

Conclusion

For writing contents that the reader can expand and contract, this is a simple and very effective approach. No risk of the JavaScript misbehaving and, for that matter, no need to write the JS in the first place.