HTML now offers us a simple way of accomplishing this using the <details> element along with its child <summary> element. Let's take a look.
<details> <summary>More Information</summary> This is some text that is toggled. </details>
Renders this:
This is some text that is toggled.
This provides keyboard support out of the box. Screen readers will also announce the control's expanded/collapsed state without any additional code necessary. The initial design is not the best looking, though. Let's add some styling.
details {
position: relative;
background: #A4E6EB;
border: 1px solid black;
width: 200px;
border-radius: 5px;
}
summary {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
line-height: 25px;
cursor: pointer;
}
details p {
margin: 0;
padding: 10px;
background: white;
border-top: 1px solid black;
border-radius: 0 0 5px 5px;
}
Renders this:
This one should look prettier.
The link below toggles the expansion/collapse of additional information. This is an example of how to implement such a control with some simple Javascript.
Note: For satisfying WCAG Success Criteria 2.4.4 - Link Purpose (In Context) when meeting WCAG A and AA requirements, the "Show" and "Hide" text would need surrounding context to convey the context of the link. Understanding link purpose out of context through the link text alone is required by Success Criteria 2.4.9 - Link Purpose (Link Only), which is a WCAG level AAA requirement. Most websites and applications strive for WCAG A and AA compliance so this is generally not a requirement.
Concepts included in this example for accessibility:
The HTML:
<a href="#" onclick="togglediv()" aria-expanded="false" aria-controls="#information" id="toggleLink">Show</a> <p id="information" style="display: none;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla massa ante, tincidunt sed eros sit amet, finibus efficitur orci. Etiam a suscipit neque, ac cursus massa. Integer eros orci, porttitor et gravida nec, maximus ut sem. Suspendisse potenti. Nunc metus dui, fermentum ac est sed, ullamcorper pulvinar est. Donec cursus sit amet mauris iaculis aliquet. Vestibulum sit amet mi nec justo malesuada tincidunt. Integer sed bibendum ex, in faucibus ligula. Sed a felis sodales, blandit ante id, iaculis enim. Vestibulum rhoncus dolor arcu, at rutrum libero molestie non. Vivamus scelerisque sapien augue, vitae venenatis enim venenatis ut. Integer in odio eget nisi facilisis consequat. Aliquam bibendum nulla ex, non porttitor neque posuere bibendum.</p>
The JavaScript
function togglediv() {
var div = document.getElementById("information");
var link = document.getElementById("toggleLink");
var value = link.getAttribute("aria-expanded");
div.style.display = div.style.display == "none" ? "block" : "none";
event.preventDefault();
if (value == "false") {
link.setAttribute("aria-expanded", "true");
link.innerHTML = "Hide";
} else {
link.setAttribute("aria-expanded", "false");
link.innerHTML = "Show";
}
}