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>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?