Today I wanna share the javascript code I used in this website for auto hiding and auto showing the sticky header menu. This code is more robust than other existing methods.

The robust auto hide, auto show effect

I prefer to use the fadeOut() and fadeIn() effect, because the fade animation can be stopped (or paused) during execution. When the page is scrolled down, the header menu will fade out; when the page is scrolled up, the header menu will fade in. While the header menu is fading out, the page is scrolled up, the header menu will change to fade in effect immediately. Similarly, while the header menu is fading in, the page is scrolled down, the header menu will immediately change to fade out effect.

AutoHideStickyHeaderMenu

Javascript code

<script type="text/javascript">
if (location.pathname !== "/") {
    var scroll_auto_hide_sticky_menu = function() {
        if (window.jQuery) {
            var lastScrollTop = jQuery(window).scrollTop();
            var prevfade = 0;
            jQuery(window).scroll(function() {
                var st = jQuery(window).scrollTop();
                var delta = st - lastScrollTop;
                if (st >= 20 && delta > 20) {
                    lastScrollTop = st;
                    if (prevfade === 0) {
                        jQuery('nav.navbar:not(.navbar-transparent)').stop().fadeOut('normal');
                    } else {/*jQuery('nav.navbar:not(.navbar-transparent)').fadeOut('normal');*/
                    }
                    prevfade = 1;
                } else if (st < 20 || delta < -20) {
                    lastScrollTop = st;
                    if (prevfade === 1) {
                        jQuery('nav.navbar:not(.navbar-transparent)').stop().fadeIn('normal');
                    } else {/*jQuery('nav.navbar:not(.navbar-transparent)').fadeIn('normal');*/
                    }
                    prevfade = 0;
                }
            });
        }
    };
    window.addEventListener('DOMContentLoaded', scroll_auto_hide_sticky_menu);
}
</script>

Explanation

In this website, I use the jQuery to find the instance of the header menu. Change this code when implementing on your website.

jQuery('nav.navbar:not(.navbar-transparent)')

The header menu of the root page is always shown, remove this if if you want all the header menus take auto hide effect.

if (location.pathname !== "/")

0 Comments

Leave a Reply

Your email address will not be published.