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.
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.
Share Improve this question edited Dec 17, 2013 at 12:55 user2672373 asked Dec 17, 2013 at 12:48 user2979139user2979139 1612 silver badges12 bronze badges 1- 1 this can help you stackoverflow./questions/487073/… – MaVRoSCy Commented Dec 17, 2013 at 12:52
4 Answers
Reset to default 6There'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!
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");
}
});
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) {
Try:
$(window).scroll(function(){
//your code
});