0

I am using JavaScript to detect when an element is visible on scroll like this..

function isOnScreen(elem) {
    // if the element doesn't exist, abort
    if( elem.length == 0 ) {
        return;
    }
    var $window = jQuery(window)
    var viewport_top = $window.scrollTop()
    var viewport_height = $window.height()
    var viewport_bottom = viewport_top + viewport_height
    var $elem = jQuery(elem)
    var top = $elem.offset().top
    var height = $elem.height()
    var bottom = top + height

    return (top >= viewport_top && top < viewport_bottom) ||
    (bottom > viewport_top && bottom <= viewport_bottom) ||
    (height > viewport_height && top <= viewport_top && bottom >= viewport_bottom)
}

jQuery( document ).ready( function() {
    window.addEventListener('scroll', function(e) {
        if( isOnScreen( jQuery( '.shipping-logos' ) ) ) { /* Pass element id/class you want to check */
            alert( 'The specified container is in view.' );
        }   
    });
});

This is working well, but I am trying to change things so that the detection only happens if the screen is scrolling up? When a user is scrolling down I want the function to ignore the element.

Anyone have an example of how to achieve this?

chazsolo
  • 7,873
  • 1
  • 20
  • 44
fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • keep a variable outside of `isOnScreen` that is `last_scroll_position = 0`. At the end of isOnScreen set it to the current position, `viewport_top`. Now you can check `viewport_top < last_scroll_position` inside `isOnScreen`. If that's true you are scrolling up. – Christopher Reid Oct 17 '18 at 23:59
  • Probably you need to recalculate your own – Piterden Oct 18 '18 at 00:00
  • https://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event – epascarello Oct 18 '18 at 00:03
  • https://stackoverflow.com/questions/31223341/detecting-scroll-direction – Scott O'Toole Oct 18 '18 at 00:13

0 Answers0