Indicate navigation menu items with submenus visually and using markup. In the following example, the submenu is indicated visually by an icon. The WAI-ARIA markup aria-expanded="false" declares that the submenu navigation is presently hidden, or “collapsed”.
The fly-out functionality is created using CSS and scripting with slightly separate considerations for mouse and keyboard users.
The following example uses this CSS code to show and hide the submenus when the parent menu items are hovered:
In addition, scripting is used to slightly delay the immediate closing of submenu items when the mouse leaves the area. This delay makes it easier to use the menu when navigation by a mouse is not very precise.
In the following example, a delay of one second is added using a timer:
Submenus should not open when using the tab key to navigate through the menu, as keyboard users would then have to step through all submenu items to get to the next top-level item. Instead, consider one of the following approaches.
Use parent as toggle
Use this approach in situations where the parent menu item only summarizes the submenu and doesn’t have to carry out a function, such as linking to a web page. In this case, the submenu is opened by a script when the user activates the top-level item and closed when the focus leaves the submenu.
The following code iterates through all top-level items with the class has-submenu and adds a click event, which opens or closes the submenu depending on its state. Also, the aria-expanded attribute is set to true while the submenu is open, and to false otherwise.
Use button as toggle
For situations when the parent menu item needs to carry out a function, such as linking to a web page, a separate button can be added to the parent item, to open and close the submenu. This button can also act as a visual indicator for the presence of a submenu.
The following code adds a button to every top-level menu item with a submenu. When the button is activated, it shows or hides the submenu. The invisible label of the button is set to “show submenu” or “hide submenu”, reflecting the state of the submenu.