简体   繁体   中英

Execute code after scrolling a certain amount of pixels from a certain point (up or down)

I'm currently making an overlay that covers a sticky top bar when the user has scrolled beyond a certain point (down) and disappears when scrolling back up. However, I'd like to be able to scroll for at least 50px before the code is executed (something like a gap before the overlay is triggered).

$(function() {
var prevScroll = $(document).scrollTop(); //initial position 

$(window).scroll(function() {
    var newScroll = $(document).scrollTop(); //position from top after scrolling 

    if(newScroll > prevScroll) { // checks if the user has scrolled up or down
            var fromNew = $(document).scrollTop(); // holds value to compare with the position + gap amount

            if (fromNew > newScroll + 50) { //checks to see if scrolled for 50px
                $("#stick-start").fadeIn("fast");
                prevScroll = newScroll + 50; //initial position + scrolled amount
            };

    } else {
            var fromNew = $(document).scrollTop();

            if (fromNew > newScroll - 50) {
                if ($("#stick-start").hasClass("is-stuck")) {
                    $("#stick-start").fadeOut("fast");
                    prevScroll = newScroll - 50;
                };
            };
         };
     });
});

The condition that checks whether you're scrolling up or down works. But as it is now, the overlay just keeps fading in and out repeatedly. How do I make it so that you have to scroll at least 50px before anything happens ?

I think this should get you where you're going.

var $document = $(document);
$(window).scroll(function() {
  if ($document.scrollTop() >= 50) {
    $("#stick-start").fadeIn("fast");
  } else {
    $("#stick-start").fadeOut("fast");
  }
});

EDIT: had an error, should be good now.

$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
      $("#stick-start").fadeIn();
   } else {
       $("#stick-start").fadeOut();
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM