How to Scroll to Fix Navbar in WordPress Theme


Fixed Navbar on mouse scroll is not new but to give this nice effect, there are several methods.The simplest method is to use CSS position. Just open your theme’s  style.css file and add the following code

position:fixed;
top:0;
z-index: 500;

The above code is going to make your position fixed. and Just add the above class inside your html/php file like this

<div class"menu-header fixed">
................your code for menu goes here
</div>

But the problem with this method is it does not add that fancy effect where we want to fix out navigation system to fixed on mouse scroll then How to make our navbar fixed on mouse scroll

The code that will add this Fixed class into your desired position is given below. Copy paste this code in a new file and save this file as myscript.js file.  We saved this file in a sub-folder of our theme name “JS”

jQuery(function() {
jQuery(window).scroll(function () {
    if (jQuery(window).scrollTop() > 150) {
            jQuery('.menucolor').addClass('fixed');
    } else {
            jQuery('.menucolor').removeClass('fixed');
    }
});
}); 

The above code add fixed class in the menucolor class, inside which we have already placed our navigation system but remove the same class when total mouse scroll is less than 150px. You can increase or descrese this size as per your own requirement.

The solution is very simple you are requested to just add the below code lines in your functions.php to add jQuery. This is basically the proper method to add any Jquery or stylesheet inside your WordPress Theme.

function binarynote_scripts()  
{
    wp_enqueue_script( 'scripts', get_template_directory_uri() . '/js/myscripts.js', array( 'jquery' ),'', true );
    if ( is_singular() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); }
} 

The second line of code will actually bring the beauty of this whole code. It will add the jquery code inside your WordPress theme that will add fixed class.




Suggested Similar Articles

One Brilliant Comment - Join Discussion Now!

  1. Hi Kumar,

    Yeah its working! Thank you for your lovely article. I have been worried about this problem for a long time. I tried number of ways but nothing got succeeded. Well Thank you.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>