Adding a Sticky Menu to the Harmony Theme

The following instructions will convert the menu of the Harmony WordPress theme to a sticky menu (will stick to the top of the screen when it hits the top due to the page scrolling).
Here is a demo of the theme with the menu converted to ‘sticky’.
http://www.dallasdesign.uk/harmony/

The following instructions assume you are working with a child theme (you should be). The folder for my child theme in this example is Harmony-child.

First of all you will need to create (if you have not done so already) a style.css file in the child theme folder (wp-content/themes/Harmony-child/style.css).
Within this file add the following code:

/*
Theme Name: Harmony Child Theme
Template: Harmony
Version: 0.1
*/
@import url("../Harmony/style.css");



#main-nav.fixed {
    position: fixed;
    top: 0;
    padding-top: 5px;
    width:100%;
    margin: 0 0 0 -50%;
    left:50%;
    z-index: 1;
}

If you haven’t already created a function.php file in your child theme folder then do so.
In this file add the following code:

add_action('wp_enqueue_scripts', 'load_javascript_files');
function load_javascript_files() {
    wp_register_script('sticky_nav', get_stylesheet_directory_uri() . '/js/sticky-nav.js', array('jquery'), true );
    wp_enqueue_script('sticky_nav');
}

 

Create a js folder and in that folder create a file called sticky-nav.js.
In this file add the following code:

jQuery(document).ready(function () {
    var header = jQuery("#main-nav");
    var headerY = header.offset().top;
    jQuery(document).scroll(function () {
        var y = jQuery(document).scrollTop();


        if (y >= headerY) {
            header.addClass('fixed');
        } else {
            header.removeClass('fixed');
        }
    });

    jQuery( window ).resize(function() {
        header = jQuery("#main-nav");
        headerY = header.offset().top;
    });
 });

 

One Comment

Leave a Reply