Toggle a dropdown menu on click in JavaScript
Intermediate · 4 min read
Dropdown menus are everywhere: the account menu in a corner, a language picker, a "Sort by" list. You click a button, a list of options drops down, and you click again (or anywhere else) to make it go away. It looks simple, and it is, as long as a few details are right.
In this tutorial you will build a button that opens and closes a list of routes, closes when you choose one, closes when you click outside it or press Escape, and tells screen readers whether it is open. You should know how addEventListener works and what an if statement is.
Hiding an element with the hidden attribute
HTML has a hidden attribute. An element that has it is not shown. JavaScript can add and remove attributes, so it can show and hide things:
list.setAttribute('hidden', '')hides the list.list.removeAttribute('hidden')shows it again.list.hasAttribute('hidden')tells you which it is, astrueorfalse.
What aria-expanded is for
A screen reader is software that reads the page aloud, used by people who can't see the screen. A sighted person sees the list appear. A screen reader user only hears what the button says about itself.
The aria-expanded attribute fills that gap. On the button, aria-expanded="true" means "the thing I control is open" and "false" means closed. aria-controls names the id of the list the button opens. Here is the page for this exercise:
<div id="menu">
<button id="trigger" type="button" aria-expanded="false" aria-controls="list">Choose a route</button>
<ul id="list" hidden>
<li><button type="button">Lagos to Abuja</button></li>
<li><button type="button">Lagos to Kano</button></li>
<li><button type="button">Lagos to Enugu</button></li>
</ul>
<p id="out">nothing chosen yet</p>
</div>
Here is the exercise. Try it on your own first, or read on and we will build it step by step.
2 A dropdown menu that opens and closes
fairA button that shows its list of options when clicked and hides them when clicked again. Make it work for a keyboard and a screen reader too.
Stuck? Three hints, smallest first
- 1. Keep the open state in one place, and derive both the visibility and the ARIA attribute from it.
- 2.
aria-expandedmust be on the button, and it must change. A screen reader has nothing else to announce. - 3. Clicking outside should close it, and so should Escape.
Step 1: one variable, one render function
The menu is either open or closed. Keep that in one variable, open, and write one function that makes the page match it.
const trigger = document.getElementById('trigger');
const list = document.getElementById('list');
let open = false;
function render() {
if (open) list.removeAttribute('hidden');
else list.setAttribute('hidden', '');
trigger.setAttribute('aria-expanded', String(open));
}
open = true;
render();
console.log(list.hasAttribute('hidden'), trigger.getAttribute('aria-expanded')); // false true
Both the visibility and aria-expanded come from the same variable, so they can never disagree. If you showed the list in one place and updated the attribute somewhere else, sooner or later one would be forgotten, and the menu would look open while announcing itself as closed.
String(open) turns the boolean into the text 'true' or 'false', because attribute values are always strings.
Step 2: toggle on click
const trigger = document.getElementById('trigger');
const list = document.getElementById('list');
let open = false;
function render() {
if (open) list.removeAttribute('hidden');
else list.setAttribute('hidden', '');
trigger.setAttribute('aria-expanded', String(open));
}
trigger.addEventListener('click', () => {
open = !open;
render();
});
render();
trigger.dispatchEvent(new Event('click', { bubbles: true }));
console.log(open); // true
trigger.dispatchEvent(new Event('click', { bubbles: true }));
console.log(open); // false
!open means "the opposite of open", so each click flips it. The { bubbles: true } makes our pretend click behave like a real one, which travels up through the page after it happens. That detail matters in Step 4.
Step 3: choose an option
You could add a listener to each of the three option buttons. One listener on the list is simpler, and it keeps working if you add more options later. When an option is clicked, the click travels up to the list, and event.target tells you which button it started on.
const out = document.getElementById('out');
list.addEventListener('click', (event) => {
if (event.target.tagName !== 'BUTTON') return;
out.textContent = `chose: ${event.target.textContent}`;
open = false;
render();
});
open = true;
render();
list.querySelector('button').dispatchEvent(new Event('click', { bubbles: true }));
console.log(out.textContent); // chose: Lagos to Abuja
console.log(open); // false
The tagName check skips clicks that land on the list itself rather than on an option. This technique of one listener on a parent is called event delegation.
Step 4: close on a click outside
A menu should also close when you click anywhere else. A listener on the whole document hears every click. Here is the first attempt:
const trigger = document.getElementById('trigger');
let open = false;
trigger.addEventListener('click', () => { open = !open; });
document.addEventListener('click', () => { open = false; });
trigger.dispatchEvent(new Event('click', { bubbles: true }));
console.log(open); // false: it opened, then closed in the same click
The menu never opens. The click on the button runs the button's listener, which sets open to true. Then the same click carries on up the page, a journey called bubbling, and reaches the document listener, which sets it straight back to false. On screen it looks as if the button does nothing.
Step 5: stop the click at the button
event.stopPropagation() tells the browser "this click goes no further up the page".
const trigger = document.getElementById('trigger');
let open = false;
trigger.addEventListener('click', (event) => {
event.stopPropagation();
open = !open;
});
document.addEventListener('click', () => { open = false; });
trigger.dispatchEvent(new Event('click', { bubbles: true }));
console.log(open); // true
document.body.dispatchEvent(new Event('click', { bubbles: true }));
console.log(open); // false: a click elsewhere closes it
Now a click on the button toggles the menu, and a click anywhere else closes it.
Step 6: close with Escape
Keyboard users expect Escape to close a menu. Key presses travel up to the document too, so one listener there catches them wherever focus is.
let open = true;
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && open) open = false;
});
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' }));
console.log(open); // true: other keys are ignored
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
console.log(open); // false
event.key is the name of the key that was pressed, such as 'Escape' or 'Enter'.
The full solution
The panel puts all of this together, with render() called after every change. Its checks confirm the menu starts closed, opens and closes on click with aria-expanded following each time, records a choice and closes, closes on an outside click and on Escape, and ignores other keys. Press Run to see it, and try the live demo with your mouse and keyboard.
allow-scripts only, so it cannot reach this page.const trigger = el('button', { id: 'trigger', type: 'button', 'aria-expanded': 'false', 'aria-controls': 'list' }, 'Choose a route');
const routes = ['Lagos to Abuja', 'Lagos to Kano', 'Lagos to Enugu'];
const list = el('ul', { id: 'list', hidden: '' },
routes.map((r) => el('li', {}, el('button', { type: 'button' }, r))));
const out = el('p', { id: 'out' }, 'nothing chosen yet');
document.body.appendChild(el('div', { id: 'menu' }, [trigger, list, out]));
// One source of truth. Everything visible is derived from it, so the visual
// state and the announced state cannot drift apart.
let open = false;
function render() {
if (open) list.removeAttribute('hidden');
else list.setAttribute('hidden', '');
trigger.setAttribute('aria-expanded', String(open));
}
trigger.addEventListener('click', (event) => {
event.stopPropagation(); // or the document listener below closes it again
open = !open;
render();
});
// Delegation: one listener for however many options there are.
list.addEventListener('click', (event) => {
if (event.target.tagName !== 'BUTTON') return;
out.textContent = `chose: ${event.target.textContent}`;
open = false;
render();
});
document.addEventListener('click', () => { if (open) { open = false; render(); } });
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && open) { open = false; render(); }
});
render();
const isOpen = () => !list.hasAttribute('hidden');
const announced = () => trigger.getAttribute('aria-expanded');
console.log('at rest : open', isOpen(), '| aria-expanded', announced());
fire(trigger, 'click');
console.log('clicked : open', isOpen(), '| aria-expanded', announced());
fire(trigger, 'click');
console.log('again : open', isOpen(), '| aria-expanded', announced());
Output
14 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 14 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('it starts closed', isOpen(), false);
test('and says so', announced(), 'false');
test('clicking opens it', (() => { fire(trigger, 'click'); return isOpen(); })(), true);
test('and the announcement follows', announced(), 'true');
test('clicking again closes it', (() => { fire(trigger, 'click'); return isOpen(); })(), false);
test('the announcement follows back', announced(), 'false');
test('the visible state and the announced state always agree', isOpen() === (announced() === 'true'), true);
test('choosing an option records it', (() => { fire(trigger, 'click'); fire(list.querySelector('button'), 'click'); return out.textContent; })(), 'chose: Lagos to Abuja');
test('and closes the menu', isOpen(), false);
test('a click outside closes it', (() => { fire(trigger, 'click'); fire(document.body, 'click'); return isOpen(); })(), false);
test('Escape closes it too', (() => { fire(trigger, 'click'); const e = new Event('keydown', { bubbles: true }); e.key = 'Escape'; document.dispatchEvent(e); return isOpen(); })(), false);
test('another key does not', (() => { fire(trigger, 'click'); const e = new Event('keydown', { bubbles: true }); e.key = 'a'; document.dispatchEvent(e); return isOpen(); })(), true);
test('there is one listener for all three options', routes.length, 3);
test('aria-controls points at the list', trigger.getAttribute('aria-controls'), list.id);
The structural idea is one open variable with a render() that derives everything from it. Toggling the visibility in one place and the ARIA attribute in another is how you end up with a menu that looks closed and announces itself as open — the assertion checking the two always agree exists to prevent exactly that.
aria-expanded is not decoration. A sighted user sees the list appear; a screen reader user has only that attribute. If it never changes, the control is silent.
event.stopPropagation() in the trigger's handler is load-bearing. Without it the click continues up to the document listener, which closes the menu the instant it opens — a bug that presents as "the menu doesn't open" and is genuinely confusing until you notice it opened and shut within one event.
Common mistakes
- Forgetting
stopPropagation()on the button. The document listener closes the menu in the same click that opened it, so the button seems broken. - Never updating
aria-expanded. The list appears for sighted users, but a screen reader keeps announcing "collapsed". - Tracking the state in two places. Hiding the list in one handler and setting the attribute in another lets them drift apart. Change
open, then callrender().
Try it yourself
- After an option is chosen or Escape is pressed, call
trigger.focus()so keyboard users land back on the button. - Add a fourth route to the HTML. Do you need any new JavaScript for it to work? Why not?
- When the menu opens, move focus to the first option with
list.querySelector('button').focus().