Almost every mobile website or mobile app have this hamburger menu button. It creates more space for your app and only visible when you really need it. Today we will look at how to create this button by AngularJS and CSS 3 animation.

Hamburger_icon.svg

Hamburger menu icon

In order to reuse our button for other projects, we should make it as an directive. Here are characteristics of our hamburger button:

  • We should be able to reuse it any time we want.
  • It should be easy to customize the menu content.
  • The open and close animation of menu should be fast. We can achieve this by using CSS3 animation.

You can take a look at demo of the menu at here: DEMO

Let’s start.

Now we create the directive first:

So in this directive, we only have to method: openMenu and closeMenu. Another important property of this directive is transclude: true. We need to turn on this property to put a <ng-transclude></ng-transclude> in directive template. <ng-transclude> will mark a place which allow to insert content into directive template.

Now the template:

Because I want to this directive is reusable in any projects so I use $templateCache to put the template of this directive into cache and the cache key is: “dt-hamburger-menu.html”.

There are 3 components in this directive:

  • A button to open menu. When menu is open it will add class “active” to .hamburger-menu-content and .hamburger-backdrop and makes them visible.
  • Menu content, inside menu content we have <ng-transclude> which is the point where we want to insert content of menu
  • A backdrop which is visible when menu is open.

The CSS

We define both appearance and animation of this directive in the css file. I added some comment in css to clarify the usage of each property.

The animation of our menu content is implemented like this:

  • At normal state, the menu is hidden because of
  • When active class is added we set value of transform property:

When transition property is defined, browser will automatically calculate the animation of the animated property. Transform property is hardware accelerated so the animation will be smooth.

Put our directive to the website:

Now everything is in place, we can use our directive simple like this:

Thanks to ng-transclude, we can customize and adapt our menu to any scenario.

Here is the usage of hamburger menu in one of my project:

AngularJS hamburger menu

Hamburger menu in a AngularJS app

I also have created a package for this menu and you can include it to your project: https://github.com/davidtran/dt-hamburger-menu

Let me know if you have feedback.

Thanks.