In this lesson, we use a bit of CSS and JavaScript to expand a menu on focus. This is important to ensure that if someone cannot use a mouse, they are still able to open the menu and see which link they are on.
Instructor: [00:00] Today, we have a navigation. When we hover over something with submenu items, it appears. The HTML is a nav, a UL, some list items, and then we have a UL with the class of submenu underneath this list item with the class of menu item.
[00:21] The problem here is when we want to focus to open that menu. If I use the tab key, tab, tab, you see that it does not show what we're tabbing to in the submenu. One might think we just need to add a pseudo-focus class here. Focus submenu.
[00:44] If you notice when we do that, it still doesn't work. This is because list items do not have a tab index and are inherently unfocusable. What I'm going to do is add a class to this item and then replace this focus pseudo-class with it.
[00:59] Here in the JavaScript, we have tap menu links. Just to note, this is not the items, this is the link itself. We're grabbing all of these. We're going to take tap menu links. This is NodeList. I'm going to use for each. I'm going to take the call back and pass it a link. Let's just console.log the link. We are getting what expect.
[01:26] What we want to target is the parent, because remember the parent is the LI above it. Here, we're going to do parentElement. Refresh that again. We have those menu items. What we're going to do is on focus of this link, we are going to add a class to the parentElement.
[01:52] Link, let's comment this out. Link addEventListener. We're going to add a focus event. I'm going to create a pre-ES6 function because I want the context of this. Let's console.log this parentElement just to be sure. We got this menu item. We got this menu item. We got this menu item.
[02:28] What we're going to do is we're going to remove this console.log and add a class focus. Let's save that. Let's look at these elements. What should be happening is we should see the focus class get added to that. Great. We know it's working. All we need to do is we need to make sure instead of having a focus pseudo-class, we're going to have a focus class. If we refresh, it opens up.
[03:04] We can optimize this a little bit more. First, let's just check the console.log, link nextElementSibling and save that. Refresh. This now means that there is no submenu underneath it. We probably only want to add this focusEventListener if there is a nextElementSibling.
[03:25] What we do here is say if this is the case, add the event listener to that link. I've refreshed now. Let's make sure only this list item gets the class focus. We're good to go.