Is there a way to determine if a certain element is currently visible on the user's screen/viewport with the use of jQuery? (not using other external libraries)
Asked
Active
Viewed 910 times
-2
-
2This has been answered many, many times before. You asked it and then answered within a minute. Why? – Oct 27 '14 at 15:36
-
@DeeMac I was searching for a question of this sort and haven't found a solution. I've posted this question right away with an answer. (the answer your own question feature) – Dropout Oct 27 '14 at 15:38
-
possible duplicate of [Check if element is visible after scrolling](http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling) – MaxiWheat Oct 27 '14 at 16:01
1 Answers
0
Not directly by using default jQuery, but you can implement your own function, which you can use one jQuery elements afterwards:
(function ($) {
$.fn.isOnScreen = function () {
var topView = $(window).scrollTop();
var botView = topView + $(window).height();
var topElement = this.offset().top;
var botElement = topElement + this.height();
return ((botElement <= botView) && (topElement >= topView));
}
})(jQuery);
After adding this code you can call $('#yourElementId').isOnScreen()
which will return true
if the whole element is on screen and false
if it's not.
You can also play around with it a bit, so it would return true
if at least a quarter of the element is visible on screen, for example like this:
(function ($) {
$.fn.isOnScreen = function () {
var topView = $(window).scrollTop();
var botView = topView + $(window).height();
var topElement = this.offset().top;
var botElement = topElement + (this.height() / 4); //<---
return ((botElement <= botView) && (topElement >= topView));
}
})(jQuery);

Dropout
- 13,653
- 10
- 56
- 109
-
nice one... but what would you do, if the element by itself is on screen, but outside of a surrounding div container with overflow:hidden? – errand Oct 27 '14 at 15:34
-
-
no, the parent is visible. something like: the parent div is 100x100px, overflow hidden and it contains 5 images with same size - only the first one would be visible and you'd have to scroll to make another one visible. but your viewport is 2000x1000px - so technically it is on screen - but it's invisible due to the overflow... – errand Oct 27 '14 at 15:38
-
@errand ah I get it now.. yeah, my answer only solves the *DOM point of view* of being *on screen*, if you can provide a solution which solves this issue as well I will be happy to learn something new and accept your answer ;) – Dropout Oct 27 '14 at 15:40
-
1:) don't see a simple solution on this one. guess you have to extend your function, to check wether one of the parents of the element has an overflow:hidden and if so, find the dimensions of this parent and check, if your element is inside these dimensions... don't forget to account for scroll bar positions, too ... well, i don't see a use case for things like that ;) – errand Oct 27 '14 at 15:49