Skip to content

Instantly share code, notes, and snippets.

@MikeNGarrett
Forked from mbjordan/mobileNav.js
Last active December 24, 2015 21:09
Show Gist options
  • Save MikeNGarrett/6862868 to your computer and use it in GitHub Desktop.
Save MikeNGarrett/6862868 to your computer and use it in GitHub Desktop.

mobileNav.js...

...is a lightweight jQuery plugin that changes anchor (<a>) elements to a drop-down list for responsive designs.

It is an alternative to TinyNav.js that does not make any assumptions about your markup, nor need any CSS for basic operation (see more below).

  • Now supports multiple navs on a page.

Use is very simple:

$('wrappingElement').mobileNav();

By default, the plugin activates when the screen is 767px wide or less. Set a custom value like this:

$('wrappingElement').mobileNav(600); // Must be an Integer

The only CSS you should need to write will be styling the actual drop-down list to match your site's theme. To do that use:

#mobileNav {/*
    my:styles;
    go:here
*/}

License: Attribution-ShareAlike 3.0 Unported Public Domain

/*
mobileNav.js by Matt Jordan.
*/
(function($) {
$.fn.mobileNav = function(mobileWidth) {
// Create the <select> element
var selectHTML = '<select name="mobileNav" class="mobileNav" style="display:none">',
currentHref = window.location.href,
checkSize = function() {
mobileWidth = mobileWidth || 767;
var width = $(window)
.width();
if (width <= mobileWidth) {
$(".mobileNav")
.show();
$(".mobileNavHide")
.hide();
} else {
$(".mobileNav")
.hide();
$(".mobileNavHide")
.show();
}
};
// Wrap the contents of the wrapping element in a control span
// Get the HREF values and text from each <a> element and fill the <select>
this.wrapInner('<span class="mobileNavHide"/>')
.find('a')
.each(function(i) {
selectHTML += '<option value="' + $(this)
.attr('href') + '"';
// If the current URL matches this elemtnts URL, set it to selected.
if (currentHref === $(this)
.attr('href')) {
selectHTML += ' selected="selected"';
}
selectHTML += '>' + $(this)
.text();
selectHTML += '</option>';
});
selectHTML += '</select>'; // End the <select>, Duh!
// Add the select to the original wrapping element
this.prepend(selectHTML);
// Set the <select> and control span to show/hide at a certain browser-width
checkSize();
$(window)
.resize(function() {
checkSize();
});
// When a new page is selected, navigate to that URL.
$(document)
.on("change", ".mobileNav", function() {
window.location.href = $(this)
.val();
});
return this; // Maintaining Chainability!
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment