Create a Responsive Navigation Menu Using jQuery

With more and more people accessing the web from mobile devices and tablets every day, it's becoming increasingly important for websites to be responsive, and one of the most important aspects of a mobile friendly website is a responsive navigation. Creating a mobile-friendly navigation menu without the use of a plugin might seem like a daunting task, but one can actually be created fairly easily with some media queries and a few lines of jQuery. Start with your standard navigation menu, which can be styled however you like, and probably looks something like this: [html] <div id="menu"> <ul> <li><a href="#">Link One</a></li> <li><a href="#">Link Two</a></li> <li><a href="#">Link Three</a></li> <li><a href="#">Link Four</a></li> </ul> </div> [/html] Next, you're going to need to add some jQuery to your code. [javascript] $("#menu").addClass("responsive").before('<div id="three-lines">&#9776;</div>'); [/javascript] This line of jQuery adds the CSS class responsive to the #menu div. and adds the div #three-lines before #menu.responsive. The #three-lines div is what creates the ☰ character that will replace the navigation menu when the screen gets to a certain width. This line of jQuery won't work properly unless we add some styling. We're going to need a media query to make sure that #menu.responsive becomes hidden when the screen gets to a certain width, and one that allows #three-lines to show up at that same point. [css] @media screen and (max-width: 700px){ #menu.responsive{ display: none; } } @media screen and (min-width: 700px){ #three-lines{ display: none; } } [/css] Now the default navigation menu will display when the browser window is above 700px, but when the window becomes smaller than 700px, it will disappear and the #three-lines icon will become visible. All that's left to do is add one more jQuery function that toggles the navigation menu when the #three-lines div is clicked. [javascript] $("#three-lines").click(function(){ $("#menu").toggle(); }) [/javascript] Now when the ☰ icon is clicked, the #menu div will appear. It will disappear if the ☰ icon is clicked a second time. Customize the responsive menu by adding your own styling or effects.