Skip to content

Instantly share code, notes, and snippets.

@tjFogarty
Created July 9, 2013 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjFogarty/5958550 to your computer and use it in GitHub Desktop.
Save tjFogarty/5958550 to your computer and use it in GitHub Desktop.
Build mobile navigation from existing list of links
var MobileNav = {
navContainer: $( '.main-nav, .ancillary-nav' ),
navItems: null,
select: null,
navHTML: "<select class=mobile-nav></select>",
optionHTML: null,
init: function() {
// Build navigation then attach event handlers
MobileNav.buildNav();
MobileNav.bindUI();
},
bindUI: function() {
$( '.mobile-nav' ).on( 'change', MobileNav.events.goToPage );
},
buildNav: function() {
var navItemLength = 0,
href = null,
text = null,
$link = null;
// Should work for multiple navigations on a single page
// Just add a selector to navContainer
$.each( MobileNav.navContainer, function(i, el) {
var $this = $( this );
MobileNav.navItems = $this.find( 'a' );
navItemLength = MobileNav.navItems.length;
$( MobileNav.navHTML ).insertBefore( $this );
// The [i] lets us select the current nav we're working on
// so all links belong to the correct navigation
MobileNav.select = $( '.mobile-nav' )[i];
// Reset optionHTML incase there are other navigation elements to rebuild
MobileNav.optionHTML = '';
// Build the <option>'s HTML to append to the <select>
for (i = 0; i < navItemLength; i++) {
$link = $( MobileNav.navItems[i] );
href = $link.attr( 'href' );
text = $link.text();
MobileNav.optionHTML += "<option value='" + href + "'>" + text + "</option>";
}
$( MobileNav.optionHTML ).appendTo( MobileNav.select );
});
// Once done, remove the old navigation and set the current page where applicable
MobileNav.navContainer.remove();
MobileNav.setCurrentPage();
},
// Find the url, and the matching on in the main navigation and set as selected option
setCurrentPage: function() {
var currentPage = window.location.pathname;
$( "option[value='" + currentPage +"']" ).prop( 'selected', true );
},
events: {
// go to a link when the user changes the navigational <select> element
goToPage: function() {
var selected = this.options[ this.selectedIndex ];
if( selected.value ) {
window.location = selected.value;
}
}
}
};
// Kick things off, maybe if $(window).width() < 768 or something
MobileNav.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment