0

I'm trying to figure out how to check if a DOM element is visible within the windows viewport during scroll, I've been using many approaches and many plugins and I'm getting nowhere. Looks like when I attach viewport checkes to window.scroll it just doesn't work:

$(window).scroll(function() {
  if(checkIfXInViewport) { 
    // this is getting executed ALL THE TIME 
  } else { 
   // this never happens even if X is NOT in viewport }
}

});

Here's an example using: http://jsfiddle.net/tuT7U/ (using https://github.com/zeusdeux/isInViewport/ ). Run the console, it always returns "visible" even if header is out of the viewport.... Why?

What am I doing wrong?

Wordpressor
  • 5,847
  • 19
  • 58
  • 93
  • possible duplicate of ["How to tell if a DOM element is visible in the current viewport?"](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) specifically [this](http://stackoverflow.com/a/7557433/2774955) – 13ruce1337 Apr 02 '14 at 00:11

1 Answers1

0

This is what I use to detect when at least 50% of the element is within the viewport then do something. You can adjust to detect the instant it becomes visible.

// Create jQuery Method

jQuery.fn.isOnScreen = function(){

  var win = $(window);

  var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
  };
  viewport.right = viewport.left + win.width();
  viewport.bottom = viewport.top + win.height();

  var elemtHeight = this.height()/2;
  elemtHeight = Math.round(elemtHeight);r

  var bounds = this.offset();
  bounds.top = bounds.top + elemtHeight;
  bounds.right = bounds.left + this.outerWidth();
  bounds.bottom = bounds.top + this.outerHeight();

  return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

}

//Usage:
$(window).scroll(function(){
  if( $('#your-element').isOnScreen() ){
    // do something
  }
  else {
    // element not in viewport
  }
});
Jason Ellis
  • 456
  • 6
  • 15