Sticky Nav on Scroll Up

by Michael Mandarino

HTML

<header>
    <ul>
        <li><a href="">menu item</a></li>
        <li><a href="">menu item</a></li>
        <li><a href="">menu item</a></li>
    </ul>
</header>
<main>
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
        Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis
        tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan
        porttitor, facilisis luctus, metus</p>
</main>
<footer>
    Footer
</footer>

SCSS

body {
    background: #eee;
    padding-top: 40px;
    margin: 0;
}

header {
    background: #ddd;
    height: 50px;
    position: fixed;
    top: 0;
    transition: top 0.2s ease-in-out;
    width: 100%;
    text-align: center;
    li {
        list-style: none;
        display: inline-block;
        a {
            color: #222;
            text-decoration: none;
            padding: 0 15px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
    }
}

.slide-up {
    top: -50px; //height of header / set dynamically with JS
}

main {
    height: 2000px;
    p {
        padding: 0;
    }
}

footer {
    background: #ddd;
    height: 45px;
    line-height: 45px;
    text-align: center;
}

JavaScript

// Hide header on scroll down
var lastScrollTop = 0;
var delta = 250;
var navbarHeight = $('header').outerHeight();


$(window).scroll(function(event) {
    handleScroll();
});


function handleScroll() {
    var scrollTop = $(this).scrollTop();

    // Make scroll more than delta
    if (scrollTop > delta) {
        // If scrolled down and past the navbar, add class .nav-up.
        if (scrollTop > lastScrollTop && scrollTop > navbarHeight) {
            // Scroll Down
            $('header').addClass('slide-up');
        } else {
            // Scroll Up
            if (scrollTop + $(window).height() < $(document).height()) {
                $('header').removeClass('slide-up');
            }
        }
    }
    /*else {
        $('header').removeClass('nav-up').addClass('nav-down');
    }*/

    lastScrollTop = scrollTop;
}