I have a project for a client that necessitates a unique drop-down menu, which can be accessed by clicking or using the keyboard to navigate to it.
Currently, my solution is almost flawless, except for one issue: when you click the drop-down menu for the first time, it briefly opens and then closes again. I suspect there might be a small glitch in my JavaScript and jQuery code causing this behavior!
The desired functionality includes:
- Allowing the user to click and open a drop-down menu. (PARTIALLY ACHIEVED, but with glitches)
- Enabling the user to click on another menu, automatically closing the previous menu and opening the new one. (DONE)
- Allowing the user to click anywhere else on the page to close the open menu. (DONE)
- Facilitating tab navigation through the menu items, highlighting each link and opening the associated menu when tabbed to. (DONE)
- Ensuring that the tabbing sequence navigates through the entire menu before moving to the next link or menu, closing the previous one. (DONE)
Even though most of the functionality is working properly, the issue arises when the keyboard focus is triggered as soon as the mouse focus occurs, leading to the menu closing instantly after being opened.
I believe there might be a simple fix to this problem. Any assistance would be greatly appreciated!
JavaScript Code
$(document).ready(function() {
function toggle(select) {
closeAll(select);
if(select.hasClass("expanded")) {
select.removeClass("expanded");
} else {
select.addClass("expanded");
}
}
function closeAll(select) {
var close = $(document).find("#navigation li.select.expanded");
if(select != null) {
close = close.not(select);
}
close.removeClass("expanded")
}
$("#navigation > ul > li.select > a").click(function(event) {
event.preventDefault();
toggle($(this).parent());
});
$(document).mouseup(function(event) {
var select = $("#navigation > ul > li.select.expanded");
if(!select.is(event.target) && select.has(event.target).length === 0) {
closeAll();
}
});
$(document).on("focus", "#navigation > ul > li > a", function () {
closeAll();
if($(this).parent().hasClass("select")) {
toggle($(this).parent());
}
});
});
HTML Code
<div id="navigation">
<ul>
<li><a href="#"><i class="fa fa-home"></i> Home</a></li>
<li class="select">
<a href="#"><i class="fa fa-users"></i> Find a Society</a>
<ul>
<li><a href="#">Scotland</a></li>
<li><a href="#">North West</a></li>
<li><a href="#">North East</a></li>
<li><a href="#">Midlands</a></li>
<li><a href="#">Eastern Counties</a></li>
<li><a href="#">Central Counties</a></li>
<li><a href="#">Wales</a></li>
<li><a href="#">South West Counties</a></li>
<li><a href="#">Southern Counties</a></li>
<li><a href="#">South East Counties</a></li>
<li><a href="#">Greater London</a></li>
</ul>
</li>
</ul>
</div>
Current Design Details