I have a small project I'm currently working on where I have an image and I need to check if it is visible in the viewport. So, if the user can see it then I will trigger a function but if not then the program will do nothing. This is pretty simple to accomplish in jQuery but I'm trying to only use javascript.
Asked
Active
Viewed 248 times
0
-
I didn't know that jQuery is not Javascript. – user123444555621 Aug 06 '14 at 04:31
-
1Nope, jQuery is built on top of javaScript, it's just a library for helps you use javaScript. It help you by use built in methods and helper functions. http://en.wikipedia.org/wiki/JQuery – Pedro Aug 06 '14 at 04:58
-
You seem to be confusing JavaScript with the [DOM](http://en.wikipedia.org/wiki/Document_Object_Model) APIs here. – user123444555621 Aug 06 '14 at 06:10
3 Answers
1
I would use getBoundingClientRect
:
function on_screen(elt) {
var rect = elt.getBoundingClientRect();
return rect.top <= window.scrollY + window.innerHeight &&
rect.bottom >= window.scrollY &&
rect.left <= window.scrollX + window.innerWidth &&
rect.right >= window.scrollX;
}
-1
var myStyle = document.getElementById("myDiv").offsetLeft;
if(myStyle < 0){
alert("Div is hidden!!");
}
second option
function isHidden(el) {
var style = window.getComputedStyle(el);
return (style.display === 'none')
}
if(isHidden(document.getElementById("myDiv"))){
alert("Hidden");
}

Vicky
- 603
- 5
- 6
-
1The first one won't work at all since offsetLeft is computed against the offset parent. Also, even if it is less than 0, some part of the element might still be visible. The second one won't work at all since a parent element could have `display: none`, and `getComputedStyle` on the child element will not reflect that. – Aug 06 '14 at 04:37
-2
Try this:
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemPos = $(elem).position();
var elemTop = elemPos.top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
var elem = $('.yourElement');
isScrolledIntoView(elem);
If your element is in view port method return true, if not in view port return false

prakashstar42
- 677
- 1
- 6
- 16
-
This fails in the case that the element is off to the left or right. Also, I thought the OP was looking for a non-jQuery solution. – Aug 06 '14 at 12:10