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

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Use Semantic HTML to Improve Hamburger Menu Accessibility

    Lindsey KopaczLindsey Kopacz
    htmlHTML 5

    Instead of using divs to create a Hamburger Menu, we are going to improve the accessibility using Semantic HTML.

    You'll see that a simple adjustment from a div to a button allows users to navigate our menu with their keyboard.

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: Today, we have a hamburger menu that we just click to open. When we click it, it just whooshes in from the left. We have a problem here. When we use our tab key -- tab, tab, tab -- I don't know if you noticed, but it went right past that hamburger menu. If you were unable to use a mouse, how would you access the menu?

    We're going to fix this. Let's take a look at the code. We have a div with the class hamburger. We have three spans with the class hamburger-line. These spans are just the three lines of the hamburger menu.

    Now let's take a look at the JavaScript. We have two variables. The first variable is hamburger-toggle. That takes the querySelector of the class hamburger. That was that wrapper of that div. Then we have the variable nav, which just takes the nav element.

    Now we add an event listener to the hamburger-toggle. This is going to be a click event. We add the function here. Notice it is not an arrow function because we want to use the context of this here. We do two things here. On nav, we toggle the class to open. We toggle the hamburger-toggle, i.e., this. We toggle that class to toggled.

    How do we fix this? It's pretty simple. We take the div and change it to the more semantic element of button. We save it. Then we go back here. Then, when we press the tab key, you see it goes into focus. We press the enter key. It opens and closes.