A simple function to create a mobile drop-down menu from a HTML list

Create an HTML menu as follows:

<nav>
   <ul>
       <li><a href="#">Link</a></li>
       <li>
           <ul class="subnav">
                <li><a href="#">Link</a></li>
                ...
           </ul>
       </li>
       <li><a href="#">Link</a></li>
       ...
   </ul>
</nav>

Add jquery and this your javascript:


// JavaScript Document
$(window).ready(function(){
       initialisemobileselectmenu();
}

function initialisemobileselectmenu()
{

	// Add a select bo to HTML element "nav"
	$("<select />").appendTo("nav");
	
        // Add an option to the top called "Menu"
        $("<option />", {
	   "selected": "selected",
	   "value"   : "",
	   "text"    : "Menu"
	}).appendTo("nav select");

        // scroll through each list element and add 
        // an option to the select menu
	$("nav ul li a").each(function() {
		var el = $(this);
		subtext = (el.parent().parent().hasClass('subnav')) ? "- " : ""
		$("<option />", {
		 "value"   : el.attr("href"),
		 "text"    : subtext+el.text()
		}).appendTo("nav select");

	});

        // add selected to current page
	$("nav select").change(function() {
		window.location = jQuery(this).find("option:selected").val();
	});
}

Add CSS media queries to hide navigation and select boxes:

/* hide select and show list as default */
nav select { display:none; }

@media all and (max-width: 767px) { 
/* hide list and show select for smaller screens */
nav ul { display:none; }
nav select { display:block; }
}