Mobile Navigation Toggle with jQuery

Taken from web designer wall.
Here’s the demo.

This tutorial shows you how to create a mobile navigation with jQuery as seen on the sites listed above. jQuery will be used to prepend the menu icon and toggle the navigation. This trick doesn’t require any extra/un-semantic HTML tags.

HTML

Below is the sample navigation HTML used in this tutorial:

<nav id="nav-wrap">

	<ul id="nav">
		<li><a href="#">Button</a></li>
		<li><a href="#">Button</a></li>
	</ul>

</nav>

jQuery Code

Include a copy of jQuery and the function below in between thetag. The function will prepend the

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function($){

	/* prepend menu icon */
	$('#nav-wrap').prepend('<div id="menu-icon">Menu</div>');

	/* toggle nav */
	$("#menu-icon").on("click", function(){
		$("#nav").slideToggle();
		$(this).toggleClass("active");
	});

});
</script>

It will render the HTML code like this (you need to Inspect Element or view generated source code to see this):

<nav id="nav-wrap">

	<div id="menu-icon">Menu</div>

	<ul id="nav">
		<li><a href="#">Button</a></li>
		<li><a href="#">Button</a></li>
	</ul>

</nav>

CSS

I’m not going to explain every detail of the CSS code because it is pretty straight forward. Instead, I will talk about the key parts.

The #menu-icon is set to display:none initially. I used media query to change the #menu-icon to display:block if the viewport width is smaller than 600px.

In the media query, I set the navigation to display:none so it is hidden initially on mobile. When the #menu-icon is clicked, it will toggle the navigation as specified in the jQuery function at the above step.

Revisions

Tags: , ,

No comments yet.

Leave a Reply