I have a simple dropdown and I want to have the possibility that the user can navigate via keyboard arrows (up/down) in the dropdown.
Here is the code:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropbtn {
background-color: #3498DB;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover, .dropbtn:focus {
background-color: #2980B9;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #ddd;}
.show {display: block;}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
This works fine when I am using tab
, but I want to use arrows (up/down), can anybody try to help me with this?
You could write a function that listens for keystrokes (when the dropdown is open), determine the key and change the focus accordingly.
Mihalma!
So, by scrounging around on the internet (keywords "HTML5 keyboard navigable dropdown"), I found this: https://dev.to/emmabostian/creating-a-custom-accessible-drop-down-3gmo
You can use a element around your dropdown.
Sadly, this makes for some pretty trashy looking styling, which is what the rest of the article is for.
Don’t forget to remove eventListener as soon as you select a dropdown option and close
just add keydown event on dropdown ,play with the focus and cancel the scrolling
I would add the listeners to the dropdown and its content, rather than the entire page.
You can call
focus()
on the previous/next child by storing a selected index using the drop-down’sdataset
property.