Convert an accessible hamburger button to vue
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
- add
v-on:click="toggleButton = !toggleButton
to change the value betweentrue
andfalse
when the button is pressed. - change
aria-expanded="false"
tov-bind:aria-expanded="toggleButton ? 'true' : 'false'
. The reason for the ternary is that a boolean value offalse
is used, the markup on the button will bearia-expanded=
insteadaria-expanded="false"
. - bind a
class
attribute to the button by addingv-on:class="{'opened' : toggleButton}"
. Vue will automatically merge the twoclass
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.