Add Padding On Scroll

How can I make it to where when a user is scrolling manually and reaches a certain class(in this example it is "content", that I add a top padding of 50px to a class named navigation.

This is what I have but it isn't working, any help is appreciated.

window.onscroll = function() {
  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
  if (scrollTop >= document.getElementsByClassName("content").offsetTop) {
    document.getElementsByClassName("navigation").style.paddingTop = "50px";
  } else {
    document.getElementsByClassName("navigation").style.paddingTop = "0px";
  }
}

Answers 1

  • getElementsByClassName() returns an array-like object, so you need to reference the index of the element you want to change when you use it. Or you can give those elements an id instead and use getElementById()

    window.onscroll = function() {
      var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
      if (scrollTop >= document.getElementsByClassName("content")[0].offsetTop) {
        document.getElementsByClassName("navigation")[0].style.paddingTop = "50px";
      } else {
        document.getElementsByClassName("navigation")[0].style.paddingTop = "0px";
      }
    }
    .content {
      padding-top: 100px;
      height: 300vh;
    }
    .navigation {
      background: #eee;
    }
    <div class="content">
      <div class="navigation">asdf</div>
    </div>


Related Articles