14

I've got a script that works out the distance of a list of elements from the top of the page, but I am unsure how to detect it's distance from the bottom. When it hits the bottom (well, 20px before the bottom) I want to fire an event and fade it out:

$(window).on('load resize scroll', function () {
    $('.links__item').each(function () {
        if (($(this).offset().top - $(window).scrollTop()) < 20) {
            $(this).stop().fadeTo(100, 0)
        } else {
            $(this).stop().fadeTo('fast', 1)
        }
    })
})

If anyone has any advice, much appreciated. I'm looping through the elements to detect it, so when one of them hits 20px from the bottom, I want to fade it out. Thanks!

Stephen Jenkins
  • 1,776
  • 3
  • 24
  • 39

2 Answers2

15

You can use the jQuery function height() at your calculations, like:

$(window).height();
$(this).height();

Specifically, if you want to detect if the top of the element is near to the bottom of the page, you can use this calc:

if ( $(this).offset().top > ($(window).scrollTop() + $(window).height() - 20) ) // True
Hastig Zusammenstellen
  • 4,286
  • 3
  • 32
  • 45
Bruno Croys Felthes
  • 1,183
  • 8
  • 27
4

Halcyon,

I am not sure what you want to fire but you can test the bottom of the page like this

$(window).on('load resize scroll', function () {
    $('.links__item').each(function () {
        if( ($(this).offset().top > ($(window).scrollTop() + $(window).height() - 20)) {
            $(this).stop().fadeTo(100, 0)
        } else {
            $(this).stop().fadeTo('fast', 1)
        }
    })
})

Reason being is jQuery finds bottom of the page based upon its height

1 $(window).height();   // returns height of browser viewport
2 $(document).height(); // returns height of HTML document
Johan Rheeder
  • 319
  • 4
  • 23