Use Semantic HTML to Improve Hamburger Menu Accessibility

Lindsey Kopacz
InstructorLindsey Kopacz
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

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.

Instructor: [00:00] 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?

[00:21] 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.

[00:35] 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.

[00:54] 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.

[01:19] 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.