Snippets: Sticky Header on Scroll Up

The code below will allow you to create a sticky function for your main header which shows only when scrolling up. Here is a basic example of what that would look like - https://cl.ly/oUZW - the concept is very simple. The javascript adds a "myprefix-maybe-sticky" class to the header when you scroll past the header and then we use CSS to give this a fixed position and an opacity of 0 so it's hidden. Then whenever you scroll up the script it adds a "myprefix-show" class which we then use via CSS to give the header an opacity of 1 so it's visible.

add_action( 'wp_head', function() { ?>
	<style>
		.myprefix-maybe-sticky {
		    position: fixed !important;
		    top: -100px;
		    width: 100%;
		    z-index: 999;
		    opacity: 0;
		    background: #fff;
		    transition: 0.3s all;
		    box-shadow: 0 2px 3px rgba(0,0,0,0.15);
		}

		.myprefix-show {
		    top: 0;
		    opacity: 1;
		}
	</style>
<?php } );

add_action( 'wp_footer', function() { ?>

	<script>

		( function( $ ) {

			'use strict';

			var $window       = $( window );
			var lastScrollTop = 0;
			var $header       = $( '#site-header' );
			var headerBottom  = $header.position().top + $header.outerHeight( true );

			$window.scroll( function() {

					var windowTop  = $window.scrollTop();

					// Add custom sticky class 
					if ( windowTop >= headerBottom ) {
						$header.addClass( 'myprefix-maybe-sticky' );
					} else {
						$header.removeClass( 'myprefix-maybe-sticky' );
						$header.removeClass( 'myprefix-show' );
					}

					// Show/hide
					if ( $header.hasClass( 'myprefix-maybe-sticky' ) ) {
						if ( windowTop <= headerBottom || windowTop < lastScrollTop ) {
							$header.addClass( 'myprefix-show' );
						} else {
							$header.removeClass( 'myprefix-show' );
						}
					}

					lastScrollTop = windowTop;

			} );

		} ( jQuery ) );

	</script>

<?php } );
All PHP snippets should be added via a child theme's functions.php file.