Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to detect when an element is near the bottom of the page

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!

like image 528
Stephen Jenkins Avatar asked May 15 '13 16:05

Stephen Jenkins


People also ask

How do you find the position of an element in a page?

The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

Is element visible on screen jQuery?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.


2 Answers

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
like image 181
Bruno Croys Felthes Avatar answered Oct 03 '22 17:10

Bruno Croys Felthes


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
like image 28
Johan Rheeder Avatar answered Oct 03 '22 19:10

Johan Rheeder