How to Integrate responsive-nav.js into WordPress Navigation

Responsive Web Design is all the rage these days. Clients are asking for it, web developers are expected to know it, and most importantly, mobile devices are more popular than ever. One big area of a website is website navigation. In my post, I talk all about responsive navigation and how to make it work nicely in WordPress.

responsive-nav.js is a fantastic, and more importantly, light-weight, piece of javascript code that will automatically switch out your current, full-width navigation for an animated pull-down section on mobile. In this post, we will:

  1. Define our menu
  2. Enqueue responsive-nav.js and accompanying CSS
  3. Add the javascript that does the heavy lifting to our template

So let’s start with the easy part: defining new menu. In functions.php of current theme:

<?php 
if ( function_exists( 'add_theme_support' ) ) { 
    add_theme_support( 'menus' );
}
?>

Then add this to your header.php (or wherever you want to add the menu):

<nav class="nav-menu">
    <?php wp_nav_menu( array('menu' => 'Main' )); ?>
</nav>

Perfect! Now you can choose the “Main” menu from the WordPress Menu admin section. Next, Enqueue responsive-nav.js. Now head over to responsive-nav.com and download the files. I always place theme-specific javascript and it’s CSS in a folder called /js/ in the theme folder.

Now, Again open up functions.php and add this:

<?php 
function responsive_scripts() {
    wp_enqueue_script('responsive-nav', get_template_directory_uri() .'/js/responsive-nav.js');
    wp_enqueue_style('resnav-css', get_template_directory_uri() .'/css/responsive-nav.css');
}
add_action( 'wp_enqueue_scripts', 'responsive_scripts' );

function responsive_footer_script(){
 echo '<script>
           var navigation = responsiveNav(".nav-menu", {
               label: "- navigate -"
           });
       </script>';
}
add_action( 'wp_footer', 'responsive_footer_script' );
?>

The above code will properly add the script & CSS to the of your theme.

That’s it! Now you have a responsive nav menu in your website.

Leave a Reply

Your email address will not be published. Required fields are marked *