How can I determine the direction of a jQuery scroll event?

后端 未结 25 1442
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 22:24

I\'m looking for something to this effect:

$(window).scroll(function(event){
   if (/* magic code*/ ){
       // upscroll code
   } else {
      // downscrol         


        
相关标签:
25条回答
  • 2020-11-21 23:02

    Scroll Event

    The scroll event behaves oddly in FF (it is fired a lot of times because of the smoothness scrolling) but it works.

    Note: The scroll event actually is fired when dragging the scroll bar, using cursor keys or mousewheel.

    //creates an element to print the scroll position
    $("<p id='test'>").appendTo("body").css({
        padding: "5px 7px",
        background: "#e9e9e9",
        position: "fixed",
        bottom: "15px",
        left: "35px"
    });
    
    //binds the "scroll" event
    $(window).scroll(function (e) {
        var target = e.currentTarget,
            self = $(target),
            scrollTop = window.pageYOffset || target.scrollTop,
            lastScrollTop = self.data("lastScrollTop") || 0,
            scrollHeight = target.scrollHeight || document.body.scrollHeight,
            scrollText = "";
    
        if (scrollTop > lastScrollTop) {
            scrollText = "<b>scroll down</b>";
        } else {
            scrollText = "<b>scroll up</b>";
        }
    
        $("#test").html(scrollText +
          "<br>innerHeight: " + self.innerHeight() +
          "<br>scrollHeight: " + scrollHeight +
          "<br>scrollTop: " + scrollTop +
          "<br>lastScrollTop: " + lastScrollTop);
    
        if (scrollHeight - scrollTop === self.innerHeight()) {
          console.log("► End of scroll");
        }
    
        //saves the current scrollTop
        self.data("lastScrollTop", scrollTop);
    });
    

    Wheel Event

    You also may take a look at MDN, it exposes a great information about the Wheel Event.

    Note: The wheel event is fired only when using the mousewheel; cursor keys and dragging the scroll bar does not fire the event.

    I read the document and the example: Listening to this event across browser
    and after some tests with FF, IE, chrome, safari, I ended up with this snippet:

    //creates an element to print the scroll position
    $("<p id='test'>").appendTo("body").css({
        padding: "5px 7px",
        background: "#e9e9e9",
        position: "fixed",
        bottom: "15px",
        left: "15px"
    });
    
    //attach the "wheel" event if it is supported, otherwise "mousewheel" event is used
    $("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) {
        var evt = e.originalEvent || e;
    
        //this is what really matters
        var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel
            scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari
            scrollText = "";
    
        if (deltaY > 0) {
            scrollText = "<b>scroll down</b>";
        } else {
            scrollText = "<b>scroll up</b>";
        }
    
        //console.log("Event: ", evt);
        $("#test").html(scrollText +
          "<br>clientHeight: " + this.clientHeight +
          "<br>scrollHeight: " + this.scrollHeight +
          "<br>scrollTop: " + scrollTop +
          "<br>deltaY: " + deltaY);
    });
    
    0 讨论(0)
  • 2020-11-21 23:02

    You can use this as well

    $(document).ready(function(){
    
      var currentscroll_position = $(window).scrollTop();
    $(window).on('scroll', function(){
    Get_page_scroll_direction();
    });
    
    function Get_page_scroll_direction(){
      var running_scroll_position = $(window).scrollTop();
      if(running_scroll_position > currentscroll_position) {
          
          $('.direction_value').text('Scrolling Down Scripts');
    
      } else {
           
           $('.direction_value').text('Scrolling Up Scripts');
    
      }
      currentscroll_position = running_scroll_position;
    }
    
    });
    .direction_value{
      position: fixed;
      height: 30px;
      background-color: #333;
      color: #fff;
      text-align: center;
      z-index: 99;
      left: 0;
      top: 0;
      width: 100%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="direction_value">
    </div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>

    0 讨论(0)
  • 2020-11-21 23:05

    Since bind has been deprecated on v3 ("superseded by on") and wheel is now supported, forget wheelDelta:

    $(window).on('wheel', function(e) {
      if (e.originalEvent.deltaY > 0) {
        console.log('down');
      } else {
        console.log('up');
      }
      if (e.originalEvent.deltaX > 0) {
        console.log('right');
      } else {
        console.log('left');
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h1 style="white-space:nowrap;overflow:scroll">
                                                                        
    0 讨论(0)
  • 2020-11-21 23:06

    To ignore any snap / momentum / bounce back at the top and bottom of the page, here is a modified version of Josiah's accepted answer:

    var prevScrollTop = 0;
    $(window).scroll(function(event){
    
        var scrollTop = $(this).scrollTop();
    
        if ( scrollTop < 0 ) {
            scrollTop = 0;
        }
        if ( scrollTop > $('body').height() - $(window).height() ) {
            scrollTop = $('body').height() - $(window).height();
        }
    
        if (scrollTop >= prevScrollTop && scrollTop) {
            // scrolling down
        } else {
            // scrolling up
        }
    
        prevScrollTop = scrollTop;
    });
    
    0 讨论(0)
  • 2020-11-21 23:07

    Keep it super simple:

    jQuery Event Listener Way:

    $(window).on('wheel', function(){
      whichDirection(event);
    });
    

    Vanilla JavaScript Event Listener Way:

    if(window.addEventListener){
      addEventListener('wheel', whichDirection, false);
    } else if (window.attachEvent) {
      attachEvent('wheel', whichDirection, false);
    }
    

    Function Remains The Same:

    function whichDirection(event){
      console.log(event + ' WheelEvent has all kinds of good stuff to work with');
      var scrollDirection = event.deltaY;
      if(scrollDirection === 1){
        console.log('meet me at the club, going down', scrollDirection);
      } else if(scrollDirection === -1) {
        console.log('Going up, on a tuesday', scrollDirection);
      }
    }
    

    I wrote a more indepth post on it here ​​​​​​​

    0 讨论(0)
  • 2020-11-21 23:08

    You can do it without having to keep track of the previous scroll top, as all the other examples require:

    $(window).bind('mousewheel', function(event) {
        if (event.originalEvent.wheelDelta >= 0) {
            console.log('Scroll up');
        }
        else {
            console.log('Scroll down');
        }
    });
    

    I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll, the event being listened for is a 'scroll' event.

    But if you specifically listen for a mousewheel event by using bind, the originalEvent attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta. If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down.

    My guess is that mousewheel events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call event.preventDefault() at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.

    0 讨论(0)
提交回复
热议问题