Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

    Collapse a Submenu on the blur Event to Improve Navigation Accessibility

    Lindsey KopaczLindsey Kopacz
    javascriptJavaScript

    In this lesson, we extend off Expand a Menu on a focus Event to Improve Navigation Accessibility to improve the navigation. We use a bit of JavaScript to collapse the submenu on blur. This is important to ensure that if someone cannot use a mouse, they are still able to close the menu.

    https://developer.mozilla.org/en-US/docs/Web/API/Element/blur_event

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 When we tab to the submenu links, notice that it does not close. What we have to do is make sure that when we tab away from this last submenu item, we remove the focus class. Let's explore this a little bit more through code.

    00:18 We're going to do const submenus equals document.querySelector, all, and then submenu. Let's just console.log that, just to make sure that we have that. Perfect. Even though we only have one submenu here I'm still going to use forEach here, because if there's multiple, we want to make sure that we do the same thing for each of them.

    00:50 submenus, for each submenu. Now, let's just console.log submenu, just to make sure. All right, great. What I want to do here is I want to get all of the submenu links. I'm going to take const submenu links equals submenu, querySelector, all, submenu link.

    01:30 One last thing I'm going to do is I am going to actually turn this into an array, because I want to use the pop method. If I console.log submenu links, this is what we get. Now, I'm going to get the last menu item by popping the last item off this array.

    01:56 Now, let's refresh. Great, we have that last menu link. I'm just going to call this a variable, const lastSubmenuLink. We have all of our variables set up. What we want to do here is the last submenu link, we want to add the blur event.

    02:21 We're going to take the submenu, and we are going to grab the parent element. Great, so this item right here is where we want to remove the focus class. Let's see what happens. Great, it works.

    Discuss

    Discuss