Question

I try to detect is element is in viewport via using getBoundingClientRect();

But my case I want to add some function when (only one) element is on the viewport like click on some html anchor tag

When :

  • Element's top >= 0
  • window.scrollTop =< Element's height

Example :

Block#A (TOP=0, HEIGHT=200)

Block#B (TOP=200, HEIGHT=450)

Block#C (TOP=450, HEIGHt=600)

When top viewport is 100 so I will do something with Block#A

So far my code :

$(window).scroll(function() {
  var elements = $('.block');
  var len = elements.length;

  for(var i=0;i<len;i++){
    var element = elements[i];
    var rect = element.getBoundingClientRect();
    var statement = 'i have no idea';
    if(statement) {
         element.doSomething();
         break;
    }
  }

});

Playground : http://jsfiddle.net/5LK3U/

Was it helpful?

Solution

Done with this :

function ViewportDetect(el) {
    var rect = el.getBoundingClientRect();
    return rect.bottom > 0 && rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top