24th May 2015

A Simple Responsive Menu

For a long time I have been tinkering around with the best way to create a responsive menu and came up with the following method.

Firstly, jump into your JavaScript file and we want to define a couple of variables, the toggle button and the menu itself.

var toggle  = $('.nav__btn');
var menu    = $('.nav');

Next, we create a function that runs when our toggle button is clicked. This can be also be fadeToggle. We don’t want the hash showing in the browser’s address bar so we preventDefault (Only if you use an a tag). This function basically toggles the menu open and closed and the toggle button’s class.

$(function() {
  toggle.on('click', function(e) {
    e.preventDefault();
    menu.slideToggle( 100 );
    toggle.toggleClass('active');
  });
});

Finally, for the jQuery, we want to remove any styling and go back to the normal menu if the browser width is over 768px (or whatever you want).

$(window).resize(function(){
  var w = $(window).width();
  if(w > 768 && menu.is(':hidden')) {
    menu.removeAttr('style');
  }
});

The HTML and CSS are very simple and you can check it all out over on CodePen.