What's new? | Help | Directory | Sign in
Google
             
Search
for
Updated Nov 15, 2008 by pilgrim
Labels: is-article, about-dom
ArticleAboveTheFold  
HOWTO detect if an element is located within the visible viewport

TODO intro

The code

This code relies on functions explained elsewhere:

/**
 * Returns the position relative to the client viewport.
 * @param {Element|Event} el Element or a mouse event object.
 * @return {goog.math.Coordinate} The position.
 */
goog.style.getClientPosition = function(el) {
  var pos = new goog.math.Coordinate;
  if (el.nodeType == goog.dom.NodeType.ELEMENT) {
    if (el.getBoundingClientRect) { // IE
      var box = el.getBoundingClientRect();
      pos.x = box.left;
      pos.y = box.top;
    } else {
      var scrollCoord = goog.dom.getPageScroll(
          goog.dom.getWindow(goog.dom.getOwnerDocument(el)));
      var pageCoord = goog.style.getPageOffset(el);
      pos.x = pageCoord.x - scrollCoord.x;
      pos.y = pageCoord.y - scrollCoord.y;
    }
  } else {
    pos.x = el.clientX;
    pos.y = el.clientY;
  }

  return pos;
};

goog.style.isAboveTheFold = function(el) {
  return goog.style.getClientPosition(element).y + element.offsetHeight <= 0;
}

The explanation

To determine if an element is "above the fold" (i.e. visible in the current browser window), we need three pieces of information:

  1. The element's position on the page
  2. The height of the browser window
  3. How far down you've already scrolled (if at all)

The goog.style.getClientPosition function handles the first 2...

TODO


Sign in to add a comment