DEV Community

Dr Hossam
Dr Hossam

Posted on Edited on

What I learned building an accessible FAQ accordion as a beginner

 I'm a veterinarian learning frontend development, and I'm building my portfolio with Frontend Mentor challenges. My latest one was an FAQ accordion with HTML, CSS and vanilla JavaScript.

It looks simple, but I learned more from it than from my earlier projects. Here are the four lessons that stuck with me.

1. A button inside an h2 is the right structure

My first idea was to make the question a clickable div. But a button gives you keyboard support (Tab, Enter, Space) for free, and the heading keeps the page structure meaningful for screen readers.

<h2>
  <button type="button" aria-expanded="false" aria-controls="faq-answer-1">
    Is Frontend Mentor free?
  </button>
</h2>
<div id="faq-answer-1" hidden>
  <p>Yes, many challenges are free.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

aria-controls connects the button to the answer by its id, and aria-expanded tells assistive technology if the answer is open or closed.

2. The hidden attribute is a simple way to hide content

Instead of adding and removing classes, I toggle one attribute in JavaScript:

button.addEventListener("click", () => {
  const answer = document.getElementById(button.getAttribute("aria-controls"));
  const isOpen = button.getAttribute("aria-expanded") === "true";

  button.setAttribute("aria-expanded", String(!isOpen));
  answer.hidden = isOpen;
});
Enter fullscreen mode Exit fullscreen mode

3. Buttons don't inherit your font

My questions looked huge and used a different font. Two reasons: browsers don't pass the page font to buttons, and my button was inside an <h2>, so it inherited the heading's big default size.

.faq-question {
  font: inherit;
  font-size: 16px;
}
Enter fullscreen mode Exit fullscreen mode

4. Test suggestions instead of trusting them

My editor's AI suggested a version of the script that looked right, but it assumed the answer was the next sibling of the button. Because my button sits inside an <h2>, that returned null and crashed on the first click. Opening the browser console showed me the error right away.

Small things like checking the Network tab for 404 errors (my fonts were not loading because of wrong paths) saved me a lot of time too.

Try it

I'm working through more Frontend Mentor challenges and writing about what I learn. If you have tips for a beginner, or feedback on my accessibility choices, I'd love to hear them in the comments.

Top comments (0)