jQuery Mobile Menu plugin for Responsive Web Sites

As part of delivering a first class browsing experience for mobile, a site’s navigation often needs to be rethought for the smaller form factor. In many cases it makes sense to replace the bulky unordered list navigation with a simple dropdown menu at the top of the page. This minimises the screen real estate occupied by the menu and allows the user to see the page content earlier.

The jQuery Mobile Menu Plugin

Here at Marker we’ve developed a jQuery plugin to do just this:

jquery-mobilemenu.js

The Mobile Menu plugin scans an existing multi-level navigation menu and dynamically builds a dropdown list which navigates the user to the selected page on the select elements change event. It is true that there are a few other plugins out there that do this already, however most of them don’t seem to handle a menu that is more than 1 level deep.

These are the steps to get it working:

1) Make sure your navigation menu is in the format:

[sourcecode type=”xml”]
<ul>
<li><a href="/">Home</a></li>
<li><a href="/services/">Services</a>
<ul>
<li><a href="/services/web-development/">Web Development</a></li>
<li><a href="/services/online-marketing/">Online Marketing</a></li>
</ul>
</li>
<li><a href="/contact-us/">Contact Us</a></li>
</ul>
[/sourcecode]

2) Add the following scripts to your website:

[sourcecode type=”html”]
<script type="text/javascript" src="/js/jquery-1.6.js"></script>
<script type="text/javascript" src="/js/jquery-mobilemenu.js"></script>
[/sourcecode]

3) Invoke the mobileMenu function on the empty dropdown list you wish to have populated:

[sourcecode type=”javascript”]
<script>
jQuery(document).ready(function($) {
  $("ddlMobileNav").mobileMenu({ ulsource : "#main-nav > ul", maxlevel : 4 });
});
</script>
[/sourcecode]

The parameters you can specify for the mobileMenu function are:

ulsource
The jquery selector referencing your unordered list.

maxlevel
The maximum number of levels of the main navigation you wish to traverse.

The Completed Select Dropdown Menu

You should now have a dropdown menu that will navigate the user to the selected page. With a bit of CSS wizardry (not supplied), this might look as follows:

mobile menu example

Media Queries

And finally, don’t forget to use media queries to hide the main navigation when the screen size is below a certain width, and likewise to hide the select menu when the screen width is larger than mobile.

Enjoy!

More about Responsive Design