Skip to content

Instantly share code, notes, and snippets.

@jaredatch
Last active October 12, 2015 12:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaredatch/4027158 to your computer and use it in GitHub Desktop.
Save jaredatch/4027158 to your computer and use it in GitHub Desktop.
dynamic mobile nav
/**
* Dynamically create a select element for the mobile navigation.
*
* @author Thomas Griffin
* @param obj $nav The main navigation object
* @param obj $ The main jQuery object
*/
function ResponsiveNav(nav, $){
/** Clone the nav, set the ID and use a concat var to store our data */
var nav_clone = $(nav).clone();
var id = '#' + $(nav_clone).attr('id');
var concat = '';
//console.log(nav_clone);
/** Create the dropdown base and general option */
concat += '<select class="menu-primary-mobile">';
concat += '<option value="" selected="selected">Menu</option>';
/** Populate the dropdown menu with items */
$.each(nav_clone, function(){
$(this).find('a').each(function(i, el){
var el = $(this);
var sep = false;
switch ( $(this).parents('.sub-menu').length ) {
case 3 : sep = '--- '; break;
case 2 : sep = '-- '; break;
case 1 : sep = '- '; break;
}
if ( sep )
concat += '<option value="' + el.attr('href') + '">' + sep + el.children().remove().end().text() + '</option>';
else
concat += '<option value="' + el.attr('href') + '">' + el.children().remove().end().text() + '</option>';
});
});
/** Append the new menu to our current menu */
concat += '</select>';
$(nav).parent().append(concat);
/** Go to the href on user selection */
$('.menu-primary-mobile').change(function(){
window.location = $(this).find('option:selected').val();
});
}
jQuery(function($){
var mobile_nav_displayed = false;
function show_mobile_nav() {
if ( $(window).width() <= 600 && mobile_nav_displayed == false) {
$('.primary-nav').hide();
$('.primary-nav').each(function(i, el){
ResponsiveNav(el, $);
});
mobile_nav_displayed = true;
} else if ( $(window).width() > 600 && mobile_nav_displayed == true ) {
$('.primary-nav').show();
$('.menu-primary-mobile').remove();
mobile_nav_displayed = false;
}
}
show_mobile_nav();
$(window).resize(show_mobile_nav);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment