DEV Community

Joanne
Joanne

Posted on

Day 16 - Make A Simple Animated Nav Button

I have been enjoying making animated navigation buttons - the ones that change from hamburger lines to an X when the navigation bar is opened. This time around, as I update my portfolio, I wanted to build one from scratch instead of reusing my previous buttons.

example gif

The one I made is in the shape of a circle. First, I made the button container and the hamburger lines.

Set Up

html set up

css set up


CSS set up

I also created a class for CSS flex to align everything inside the hamburger wrapper vertically and horizontally.

flex center

Since the hamburger line class was already assigned to the three divs in the html file, we should see the following:

example starting point

I chose the following transformations to make the X:

  • Top line will rotate 45 degrees and move down 10px
  • Middle line will disappear
  • Bottom line will rotate the opposite way -45 degrees and move up 10px

line classes

In this example, the animations are done by using the CSS transition property. So I added a class for the transition property and assigned it to our hamburger lines:

transition property

assigned transition

Unique identifiers were set for the top, middle, lines in order to select them with Javascript. In this one I used ids.

ids example

Almost done! Using Javascript, I can dynamically toggle the classes ending with "-animate" so the transition property smoothly changes the lines to create an X.

The Javascript code should do the following:

  • Find the button element in the html document
  • Create a function that toggles the "-animate" class names in the html elements
  • Create an event listener on the button element that calls the function to activate the transition property every time the button is clicked

Alt Text

Check out the entire code here.

What I Learned

I was able to practice building navigation buttons from my memory!

How This Will Help Me

I can get more creative with interactive navigation buttons!

Top comments (0)