Smart Fixed Top Navigation In Pure JavaScript

Category: Javascript , Menu & Navigation | May 12, 2017
Author: chimp-v6
Views Total: 2,963
Official Page: Go to website
Last Update: May 12, 2017
License: MIT

Preview:

Smart Fixed Top Navigation In Pure JavaScript

Description:

Just another JavaScript solution to create a smart site navigation that auto hides on scroll down and reveals itself again on scroll up.

How to use it:

Create a normal header navigation as this:

<header class="header-navigation" id="header">
  <nav>
    <a class="link" href="#" title="Home">Home</a>
    <a class="link" href="#" title="About">About</a>
    <a class="link" href="#" title="Contact">Contact</a>
  </nav>
</header>

Make the header navigation sticky on page load.

.header-navigation {
  position: fixed;
  top: 0;
  width: 100%;
  height: 60px;
  line-height: 60px;
  background-color: #333;
  text-align: center;
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
}

The JavaScript to auto show/hide the header navigation depending on the scroll position.

var new_scroll_position = 0;
var last_scroll_position;
var header = document.getElementById("header");

window.addEventListener('scroll', function(e) {
  last_scroll_position = window.scrollY;

  // Scrolling down
  if (new_scroll_position < last_scroll_position && last_scroll_position > 80) {
    // header.removeClass('slideDown').addClass('slideUp');
    header.classList.remove("slideDown");
    header.classList.add("slideUp");

  // Scrolling up
  } else if (new_scroll_position > last_scroll_position) {
    // header.removeClass('slideUp').addClass('slideDown');
    header.classList.remove("slideUp");
    header.classList.add("slideDown");
  }

  new_scroll_position = last_scroll_position;
});

Apply smooth slide up/down animations to the header navigation.

.slideUp {
  -webkit-transform: translateY(-100px);
  transform: translateY(-100px);
  transition: transform .5s ease-out;
}

.slideDown {
  -webkit-transform: translateY(0);
  transform: translateY(0);
  transition: transform .5s ease-out;
}

You Might Be Interested In:


Leave a Reply