Navigation is one of the most challenging battles for doing responsive design well. To preface this article, I highly recommend you study Brad Frost’s collections of responsive navigation patterns and complex responsive navigation patterns. In this post, I’ll cover two methods for handling the “toggle” method for responsive navigation in WordPress.
Common responsive navigation patterns in WordPress
There are many possible approaches to responsive navigation. But other than the “do nothing” approach, the “toggle” method for handling responsive navigation is by far the most popular I’ve seen in WordPress themes.
The toggle method is typically represented by a button with text or a “hamburger” icon replacing an inline navigation method once the screen size shrinks to a particular size. The trigger for the toggle method is where I’d like to focus.
Toggle Method 1 — jQuery resize and window width
I’ve used a method very similar to this ever since I studied it in the _s theme over a year ago. Essentially, the trigger is handled by identifying the window width at any time with $( window ).width(). I’ll have a full view of a slightly updated version of this code below, but you can see this method in this gist as well.
When the window width is above 600px, the main-navigation class is utilized, and when the window is below 600px, main-small-navigation is utilized for the menu itself. Also, the h1 used for assistive text (for accessibility purposes) is altered to be the menu toggle and associated text, triggered by jQuery’s .click function.
Therefore, the menu is able to be turned into a click-activated toggled navigation method for small views.
This is a pretty good solution, and has been used quite a bit. One pet peeve of mine for this solution is the hard coded pixel value for where the menu breaks. It’s fine for if you build parent themes from starters such as _s, but distributed parent themes that anticipate child theme usage and customization should do better. We could make the hard-coded valuable filterable by PHP using wp_localize_script.
Integrate wp_localize_script for flexibility
Here’s an example alternative JavaScript file and corresponding enqueue that utilizes wp_localize_script, making the hardcoded valuable filterable with PHP.
Read more