0

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.

Pedro
  • 67
  • 8

3 Answers3

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
  • 1
    The 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