How to create keyboard-navigable menus

Creating keyboard-navigable menus enhances accessibility and user experience on your website. It enables users to navigate through menu items using keyboard keys, making it easier for those who may have difficulty using a mouse.

In this example, we will implement a simple, accessible dropdown menu using HTML, CSS, and a bit of JavaScript to ensure that users can navigate the menu using the keyboard.

<nav> <ul class="menu"> <li><a href="#">Home</a></li> <li><a href="#">About</a> <ul class="submenu"> <li><a href="#">Team</a></li> <li><a href="#">Careers</a></li> </ul> </li> <li><a href="#">Services</a></li> <li><a href="#">Contact</a></li> </ul> </nav> <style> .menu, .submenu { list-style: none; padding: 0; margin: 0; } .submenu { display: none; } .menu li:hover .submenu, .menu li:focus-within .submenu { display: block; } </style> <script> document.querySelectorAll('.menu li').forEach(item => { item.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') { const submenu = item.querySelector('.submenu'); if (submenu) { submenu.style.display = submenu.style.display === 'block' ? 'none' : 'block'; event.preventDefault(); } } }); }); </script>

keyboard-navigable menus accessible navigation HTML menu example CSS dropdown menu