My implementation focuses on making drop down menus accessible via keyboard input using HTML/CSS and JS/jQuery events.
The goal of keyboard accessibility includes:
- Tab key to navigate the menu elements.
- Pressing the down arrow key opens a focused menu.
- Using the tab key in the menu helps navigate through its elements.
- Pressing the esc key closes the drop-down menu.
- Upon closing, maintain focus on the parent element of the menu.
Check out the jsFiddle example for a full implementation.
Issue: How can I return to the initial parent element after closing the drop-down menu with the esc key? This prevents users from having to tab back to their original location.
I appreciate any help!
HTML
<ul class="menu">
<li>
<a href="#">Menu Elem</a>
<div class="subMenu">
<ul>
<li>
<a href="#">Sub Menu Elem</a>
</li>
<li>
<a href="#">Sub Menu Elem</a>
</li>
<li>
<a href="#">Sub Menu Elem</a>
</li>
</ul>
</div>
</li>
<li>
<a href="#">Menu Elem</a>
<div class="subMenu">
<ul>
<li>
<a href="#">Sub Menu Elem</a>
</li>
<li>
<a href="#">Sub Menu Elem</a>
</li>
<li>
<a href="#">Sub Menu Elem</a>
</li>
</ul>
</div>
</li>
<li>
<a href="#">Menu Elem</a>
<div class="subMenu">
<ul>
<li>
<a href="#">Sub Menu Elem</a>
</li>
<li>
<a href="#">Sub Menu Elem</a>
</li>
<li>
<a href="#">Sub Menu Elem</a>
</li>
</ul>
</div>
</li>
</ul>
CSS
.menu > li {
display: inline-block;
text-align: center;
color: white;
background-color: orange;
width: 100px;
height: 70px;
position: fixed;
}
.menu > li:hover {
cursor: pointer;
}
.menu > :nth-child(1) {
left: 1px;
}
.menu > :nth-child(2){
left: 102px;
}
.menu > :nth-child(3){
left: 203px;
}
.menu > li > a {
line-height: 70px;
}
.menu > li > .subMenu {
display: none;
width: 200px;
margin-top: 1px;
outline: 1px solid black;
}
.menu > li > .subMenu > ul > li {
height: 100px;
background-color: green;
margin-left: -40px;
line-height: 100px;
}
.menu > li > .subMenu > ul > li:hover {
background-color: purple;
cursor: pointer;
}
a {
text-decoration: none;
color: white;
}
JS/jQuery
$(document).ready(function(){
var menuElem = $(".menu > li");
$(menuElem).hover(function(){
$(this).find(".subMenu").toggle();
});
$(menuElem).keydown(function(e) {
// down arrow key
if(e.keyCode === 40 && $(this).find(".subMenu").is(":hidden")){
$(this).find(".subMenu").toggle();
}
// esc key
else if(e.keyCode === 27 && $(this).find(".subMenu").is(":visible")){
$(this).find(".subMenu").toggle();
// ***** problematic code here *****
// Need to target the <a> element, or the <li> element, or the <div>, or the <ul> element, not sure which one will work.
// Currently: trying to get whichever element represents the selected menu, in the below case the anchor element
$(menuElem).eq($(this).index()).find("a").addClass("selected");
}
});
});