Navigation is difficult enough in desktop view, but how does one deal with a potentially large navigation across multiple devices?
It seems like the standard way to deal with mobile navigation is to set the navigation to display:none;
and then toggle it with a hamburger icon. And while this is a fairly straight forward method, I’ve become fond of using a select statement and a bit of JavaScript to handle mobile navigation.
But, the problem here is that WordPress’ default markup for menus uses an un-ordered list.
Generating the Select from a WordPress Menu
Luckily, given the location id for a menu, we can retrieve a set of menu items and then coax that into any output we would like.
Below is an example of how to do this, modified from an example in the WordPress Codex.
“`<?php
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ 'menu-location' ] );
$items = wp_get_nav_menu_items($menu->term_id);
echo '<select class="fancyDropdown">';
echo '<option value="">Menu</option>';
foreach($items as $key => $item) {
echo '<option value="'.$item->url.'">'.$item->title.'</option>';
}
echo '</select>';
[code lang=text]
<br />Note that we are placing the links within the value for each option. Where we would use <code><a href="http://superhero.io"></a></code>, we are now using <code><option value="http://superhero.io"></option></code>.
Also take note of the dummy option called 'Menu'. Since this option is first in the list, it will be shown by default and the 'Menu' text will act as a visual cue for a non-standard UI.
<h3>And a Touch of Javascript</h3>
Now that we have the select built, we need a way to navigate when the select has been clicked. For that, we'll use a little bit of javascript and jQuery.
“`jQuery(document).ready(function($){
$('.fancyDropdown').change(function(){
var url = $(this).val();
if ( url.length ) {
window.location.href = url;
}
});
});
[/code]
This little bit of javascript will get the URL from the selected option (stored as a value) and then navigate the current page to that URL. There is a simple check to see that the URL has length (is not null) which will prevent performing a redirect when the dummy ‘Menu’ option is selected.
Bottom Line
While using selects for your mobile users is a fairly straightforward and simple process… it does have its fallbacks.
- It requires javascript
- Is not a standard interaction on a website.
While being a javascript solution is likely not a big issue, since slide out menus use javascript as well, you don’t want to risk confusing your visitors too much.
That being said, I think this is a solid option to be considered in working with mobile navigation. What do you think?
Leave a Reply