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: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.