user2979139
user2979139

Reputation: 161

Javascript, check if element has left the screen

I'm trying to test if a <div> has been scrolled out of view.

This is what I have so far,

$(window).on('scroll',function(){
    var divBottom    = $('#home').offset().bottom; 
    var windowTop    = $(window).scrollTop();           
    var windowBottom = windowTop + $(window).height();  

    if (divBottom >= windowTop) {
        console.log("yes");
    } else {
        console.log("no");
    }
});

No matter where I scroll, nothing is logged.

What I was trying to test is if the bottom of the div has gone past the top of the window.

Upvotes: 1

Views: 3596

Answers (4)

jeremija
jeremija

Reputation: 2528

divBottom is undefined. You can use the top offset of the element and then calculate it's bottom value by adding it's height to the top, like in this fiddle.

$(window).on('scroll',function(){
    var $home = $('#home');
    var divBottom     = $home.offset().top + $home.height(); 
    var windowTop    = $(window).scrollTop();           

    console.log(divBottom, windowTop);

    if (divBottom >= windowTop) {
        console.log("yes");
    } else {
        console.log("no");
    }
});

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

There's a very useful Vanilla JS function that could help here.

var divposition = document.getElementById('home').getBoundingClientRect();
if( divposition.left+divposition.width < 0) {
    // element is off to the left of the view
}
if( divposition.top+divposition.height < 0) {
    // element is off the top of the view
}
if( divposition.top > window.innerHeight) {
    // element is off the bottom of the view
}
if( divposition.left > window.innerWidth) {
    // element is off to the right of the view
}

Hope this helps!

Upvotes: 6

jvv
jvv

Reputation: 188

Try:

$(window).scroll(function(){ 
//your code 
});

Upvotes: 0

A Paul
A Paul

Reputation: 8251

Try this.

var myTop        = $('#home').offset().top;  // the top y location of your element
var windowTop    = $(window).scrollTop();           // the top of the window
var windowBottom = windowTop + $(window).height();  // the bottom of the window

then

if (myTop > windowTop && myTop < windowBottom) {

Upvotes: 0

Related Questions