This is an example to fix the navigation to the top of the page when scrolling down. This case scenario is a header (site-header) and a navigation under it (nav-primary).
It takes in consideration if the user is logged in to calculate the WordPress adminbar height.

functions.php

1
2
3
4
5
6
7
8
9
add_action( 'wp_enqueue_scripts', 'load_my_scripts' );
function load_my_scripts() {
 
     wp_enqueue_script( 'my-script', get_bloginfo( 'stylesheet_directory' ) . '/assets/js/my-scrip.js', array( 'jquery') );
 
     wp_localize_script( 'my-script', 'my_vars', array(
			'logged_in' => is_user_logged_in() ? 'yes' : 'no',
     ));
}

my-script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
jQuery(function( $ ){
 
	var navigation = $('.nav-primary');	
	var header     = $('.site-header');
 
	var navigation_height = parseInt( navigation.css('height') );
	var header_height     = parseInt( header.css('height') );
	var adminbar_height   = 0;
 
	if( my_vars.logged_in == 'yes' ){
		adminbar_height = 	parseInt($('#wpadminbar').css('height'));
	}
 
	$(window).scroll( function(){
 
	    var scrollTop              = $(this).scrollTop();
	    var topDistance_navigation = navigation.offset().top;
       	    var topDistance_header     = header.offset().top;
 
	    // if navigation hits the top stay fixed
	    if ( topDistance_navigation - adminbar_height < scrollTop ) {
 
                 if( ! navigation.hasClass('nav-fixed') ) {
 
            	     navigation.addClass('nav-fixed');
		     navigation.css('top', adminbar_height);
 
            	}
 
            } 
 
            // if header hits the top remove fixed class
           	if( header_height - adminbar_height  > scrollTop ) {
            	navigation.removeClass('nav-fixed');
            }
        });
 
});

style.css

1
2
3
4
5
6
.nav-primary.nav-fixed{
   position:fixed;
   left:0px; 
   width:100%;
   z-index: 500;
}
Example to fix navigation on scroll
Tagged on:

Leave a Reply

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