-4

I want to change the look of my top navigation bar when the page has been scrolled a certain number of pixels. I believe this means I need a listener for that scrolled amount? I read about element.scrollTop but that doesn't seem to be constantly 'listening' for how much the user has scrolled.

How may I achieve this effect?

Sun R
  • 1
  • 5

3 Answers3

0

Try this:

window.addEvent('scroll',function(e) {
        if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
                // enter code here
            }
});
Bar Levin
  • 89
  • 8
0

Use the following code.

$(window).scroll(function()
{
    document.getElementById("fixed_box").innerHTML = "You have Scrolled to " + $(window).scrollTop() + "px";
});
#fixed_box {
    position:fixed;
    top:10px;
    overflow:auto;
    height: 100%;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div style="height: 5000px;">
</div>
<div id="fixed_box">You have Scrolled to 0px</div>
John Doe
  • 1,401
  • 1
  • 3
  • 14
  • What exactly does $(window) mean? The code didn't work for my website and I suspect this is the culprit. I've seen people use window.document.body etc before, am I supposed to use that? – Sun R Feb 23 '21 at 18:36
  • you can use window.document.body when u dont want to use jquery. $(window) is a jquery code that does exactly the same as window.documenta.body – John Doe Feb 24 '21 at 03:12
0
window.addEventListener('scroll',handleScroll);

function handleScroll(){
      let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;

  if(scrollPosition >50)
      console.log('Viewport scrolled more than 50px')
  else
      console.log('Viewport scrolled less than 50px')

}

let firstHandlerScroll = debounce(handleScroll, 200);
window.addEventListener('scroll',firstHandlerScroll);

function handleScroll(){
      let scrollPosition = window.pageYOffset || window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;
       if(scrollPosition >=50){
         console.log('more than 50')
       }
       else
         console.log('less than 50')
   }
   
   function debounce(fn, delay) {
      let timer = null;
      return function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn();
        }, delay);
      };
    }

The first naif version is ok, but is resource consuming. The scroll event handler is called very much times. The second version in the snippet instead call the handler only when you release the mouse after scroll, thus is much kind about efficiency

Nick
  • 1,439
  • 2
  • 15
  • 28