Populate Mobile Hamburger Menu with Content of Primary Navigation Menu; WordPress

I’m writing this specifically for use in WordPress, but I’ve actually applied the same thing in multiple scenarios, including Shopify. Essentially, it’s more of a general “CMS” problem than anything else. The problem generally being that you might only be able to include one instance of a template-tag generated navigation menu. Often times, a theme will not have the ability to generate multiple menus, or you’d just rather not bother with having an additional menu.

In those instances where I was unable to achieve this in that way, and a hard-coded menu was out of the question, I just used a handy little bit of jQuery to handle the population for me.

Firstly, we need to create some empty divs to hold our menu content for mobile devices. I’ve developed a habit of using the id “hamburger train”, because of my affinity for a song by Primus entitled “Hamburger Train” (which is an example of some excellent bass and percussion). I digress. Here is how I setup my container(s):


<div id="hamburgertrain">
<ul>
<li></li><li></li><li></li>
</ul>
</div>
<div id="mobilenavigation">
</div>

The empty “li” elements, are for the purpose of creating the “bars” without the need for an image. I just give them a height and width, and a background color. Quick way to handle the problem, and removes the need for extra load time for an image (not that such a small image would make much of a difference, but every little thing adds up). The mobile navigation container is for the navigation menu itself. This div is hidden, so that it will only slide down when a user interacts with the menu button.
In the theme I’m working with, in this instance, there is the classic use of a wp-nav-menu: ‘top-menu’ ) ); ?> , and actually there are two different menus, but I don’t want to confuse the issue. All it means is an extra step in the process, and it will be included below anyways.
So, all I have to do now is grab the content of that menu, and populate my empty div with it. We do this using jQuery. I will just place the whole jQuery script, and comment it, so you can make use of it if needed:


$(document).ready(function(){ //run the function on load
$('#mobilenavigation').html($('#top-menu-left').html()); // this adds the content of the top left menu to the mobile menu
$('#mobilenavigation').append($('#top-menu-right').html()); // this adds the content of the top right menu to the mobile menu
$('#hamburgertrain').click(function () { //on clicking tapping button
$('#mobile #mobilenavigation').slideToggle(); //this slides the menu up or down on clicking/tapping the button
}); //end click/tap function
}); // end document ready function

There you go. It’s just that simple.