I’m loading elements via AJAX. Some of them are only visible if you scroll down the page. Is there any way I can know if an element is now in the visible part of the page?
Advertisement
Answer
This should do the trick:
JavaScript
x
11
11
1
function isScrolledIntoView(elem)
2
{
3
var docViewTop = $(window).scrollTop();
4
var docViewBottom = docViewTop + $(window).height();
5
6
var elemTop = $(elem).offset().top;
7
var elemBottom = elemTop + $(elem).height();
8
9
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
10
}
11
Simple Utility Function This will allow you to call a utility function that accepts the element you’re looking for and if you want the element to be fully in view or partially.
JavaScript
1
22
22
1
function Utils() {
2
3
}
4
5
Utils.prototype = {
6
constructor: Utils,
7
isElementInView: function (element, fullyInView) {
8
var pageTop = $(window).scrollTop();
9
var pageBottom = pageTop + $(window).height();
10
var elementTop = $(element).offset().top;
11
var elementBottom = elementTop + $(element).height();
12
13
if (fullyInView === true) {
14
return ((pageTop < elementTop) && (pageBottom > elementBottom));
15
} else {
16
return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
17
}
18
}
19
};
20
21
var Utils = new Utils();
22
Usage
JavaScript
1
8
1
var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);
2
3
if (isElementInView) {
4
console.log('in view');
5
} else {
6
console.log('out of view');
7
}
8