James McGrath

Convert an accessible hamburger button to vue

Apr 18, 2020
2 minutes

Today let’s see how we can refactor an accessible hamburger button using Vue.

The first thing is to fork Simple and accessible SVG menu hamburger animation in codepen.

Next let’s setup up Vue in codepen.

In the settings go to JS and search for “vue”.

Then delete delete min from the the vue file name. By doing this Vue devtools will work when the pen is viewed in debug mode.

Next in the Javascript pane add

new Vue({
    el: "#app",
    data: {}
});

In the HTML pane add


<div id="app"></div>

Vue is now setup in our pen.

Now it’s time to copy the HTML and CSS from the forked codepen to the Vue codepen. The js section is not needed because Vue will handle all of that.

After copying the HTML and CSS add a boolean to the data object in the Javascript panel. Let’s call it toggleButton and assign it a value of false.

new Vue({
    el: "#app",
    data: {
        toggleButton: false
    }
});

Next we will add a click event to the button and bind class and aria-expanded to the toggleButton boolean in data.

On the button do the following

  1. add v-on:click="toggleButton = !toggleButton to change the value between true and false when the button is pressed.
  2. change aria-expanded="false" to v-bind:aria-expanded="toggleButton ? 'true' : 'false'. The reason for the ternary is that a boolean value of false is used, the markup on the button will be aria-expanded= instead aria-expanded="false".
  3. bind a class attribute to the button by adding v-on:class="{'opened' : toggleButton}". Vue will automatically merge the two class on the button together.

The `button should look like the following:


 <button
    class="menu-toggle"
    :class="{'opened': toggleButton}"
    id="menu-toggle"
    :aria-expanded="toggleButton ? 'true' : 'false'"
    @click="toggleButton = !toggleButton"
  >...</button>

That’s it. Now the button function like the codepen that it was forked from. Here’s a working example.

See the Pen Accessible Hamburger Vue by James (@jamcgrath) on CodePen.