1

I am attempting to detect scroll on a page if it exceeds 100px from a fixed top navigation that has a height of 80px.

The plan is that once the user's scroll, exceeds the mentioned 100px, the navbar will change background color.

I have seen a lot of tutorials on the subject, but all those I have seen are using Jquery. I wish to make this using Vanilla Javascript.

carlo
  • 13
  • 1
  • 5

3 Answers3

4

you can use window.onscroll to detect scroll and window.pageYOffset or document.documentElement.scrollTop properties to get the scroll position of window. below is a code snippet for your scenario you described:

window.onscroll = function(){
var top =  window.pageYOffset || document.documentElement.scrollTop;
if (top > 100) {
 document.getElementById('nav').style.background = "blue";
} else {
 document.getElementById('nav').style.background = "yellow";
}
};
nav {
  position:fixed;
  height:100px;
  width:100%;
  top:0;
  background:yellow;
  display:block;
}
<nav id="nav">
  Hello
</nav>
<div style="height:700px;">
  
</div>
Surya Neupane
  • 906
  • 10
  • 20
1
window.onscroll = function() {
    if (window.pageYOffset > 100) {
      // Do something
    }
};
SH K
  • 112
  • 4
0

Bind an event listener to window object; window.addEventListener("scroll", callback)

Then on your callback you could make use of these properties/functions;

JS Scroll: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

JS Height: https://developer.mozilla.org/en-US/docs/Web/API/Screen/height

Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23