(function($){ //variable for storing the menu count when no ID is present var menuCount = 0; //plugin code $.fn.mobileMenu = function(options){ //plugin's default options var settings = { switchWidth: 480, topOptionText: 'Select a page', indentString: '   ' }; //function to check if selector matches a list function isList($this){ return (($this.is('ul, ol')) ? true : false); } //function to decide if mobile or not function isMobile(){ return (($(window).width() < settings.switchWidth) ? true : false); } //check if dropdown exists for the current element function menuExists($this){ //if the list has an ID, use it to give the menu an ID if($this.attr('id')){ return (($('#mobileMenu_'+$this.attr('id')).length > 0) ? true : false); } //otherwise, give the list and select elements a generated ID else { menuCount++; $this.attr('id', 'mm'+menuCount); return (($('#mobileMenu_mm'+menuCount).length > 0) ? true : false); } } //change page on mobile menu selection function goToPage($this){ if($this.val() !== null){document.location.href = $this.val()} } //show the mobile menu function showMenu($this){ $this.hide(); $('#mobileMenu_'+$this.attr('id')).show(); } //hide the mobile menu function hideMenu($this){ $this.show(); $('#mobileMenu_'+$this.attr('id')).hide(); } //create the mobile menu function createMenu($this){ if(isList($this)){ //generate select element as a string to append via jQuery var selectString = ''; //append select element to ul/ol's container $this.parent().append(selectString); //add change event handler for mobile menu $('#mobileMenu_'+$this.attr('id')).change(function(){ goToPage($(this)); }); //hide current menu, show mobile menu showMenu($this); } else { alert('mobileMenu will only work with UL or OL elements!'); } } //plugin functionality function run($this){ //menu doesn't exist if(isMobile() && !menuExists($this)){ createMenu($this); } //menu already exists else if(isMobile() && menuExists($this)){ showMenu($this); } //not mobile browser else if(!isMobile() && menuExists($this)){ hideMenu($this); } } //run plugin on each matched ul/ol //maintain chainability by returning "this" return this.each(function() { //override the default settings if user provides some if(options){$.extend(settings, options);} //cache "this" var $this = $(this); //bind event to browser resize $(window).resize(function(){run($this);}); //run plugin run($this); }); }; })(jQuery);