Skip to content

Instantly share code, notes, and snippets.

@mbjordan
Created November 19, 2012 15:01
Show Gist options
  • Save mbjordan/4111130 to your computer and use it in GitHub Desktop.
Save mbjordan/4111130 to your computer and use it in GitHub Desktop.
mobileNav.js, an alternative to tinyNav.js without markup assumption

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).

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" id="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 id="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