JS addClass, removeClass on Scroll

by Kevin Pliester

HTML

<header id="header">
  <nav id="header-menu">
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
  </nav>
</header>

SCSS

body {
  height: 4000px;
}

#header {
  position: fixed;
  height: 50px;
  background-color: #ddd;
  padding: 5px;
  width: 100%;
  top: 0;
  left: 0;
  #header-menu {
    position: relative;
    display: none;
    background-color: #fff;
    &.fade-in {
      display: block;
    }
    a {
      display: inline-block;
      color: red;
      text-decoration: none;
    }
  }
}

JavaScript

var menu = document.getElementById('header-menu')
var header = document.getElementById('header')

// function add class
Element.prototype.addClass = function(className) {
  this.classList.add(className);
}

// function remove class
Element.prototype.removeClass = function(className) {
  this.classList.remove(className);
}

// add & remove class on scroll
window.addEventListener('scroll', function() {

  var bodyOffset = window.pageYOffset
  var headerHeight = header.offsetHeight

  if (bodyOffset > headerHeight) {
    menu.addClass('fade-in')
  } else {
    menu.removeClass('fade-in')
  }
  
  console.log(bodyOffset);
  console.log(headerHeight);
})