My favorites | Sign in
Project Logo
             
Search
for
Updated Nov 15, 2008 by pilgrim
Labels: is-article, about-dom
ArticleClientViewportElement  
HOWTO find the viewport (goog.style.getClientViewportElement)

Ah, the viewport: a mysterious "special" variable that defines the canvas on which the browser paints. (Not to be confused with the canvas element, which is the canvas on which the web developer paints.) Getting a reference to the viewport is essential for calculating where an element is on the page and determining whether it is visible on screen. This function will find the viewport object.

The code

This code relies on functions explained elsewhere:

/**
 * Returns the viewport element for a particular document
 * @param {Node} opt_node DOM node (Document is OK) to get the viewport element
 *     of.
 * @return {Element} document.documentElement or document.body.
 */
goog.style.getClientViewportElement = function(opt_node) {
  var doc;
  if (opt_node) {
    if (opt_node.nodeType == goog.dom.NodeType.DOCUMENT) {
      doc = opt_node;
    } else {
      doc = goog.dom.getOwnerDocument(opt_node);
    }
  } else {
    doc = goog.dom.getDocument();
  }

  // In old IE versions the document.body represented the viewport
  if (goog.userAgent.IE && doc.compatMode != 'CSS1Compat') {
    return doc.body;
  }
  return doc.documentElement;
};

The code walkthrough

The viewport element is usually document.documentElement, except in Microsoft Internet Explorer. But that begs the question, which document? To answer that, we need to find the node's owner document. Of course, if we weren't given a specific node in the first place, we just use document and hope for the best.

  var doc;
  if (opt_node) {
    if (opt_node.nodeType == goog.dom.NodeType.DOCUMENT) {
      doc = opt_node;
    } else {
      doc = goog.dom.getOwnerDocument(opt_node);
    }
  } else {
    doc = document;
  }

In Internet Explorer, the viewport is either document.body or document.documentElement, depending on the document's compatibility mode.

  if (goog.userAgent.IE && doc.compatMode != 'CSS1Compat') {
    return doc.body;
  }
  return doc.documentElement;
};

Further reading


Comment by mad...@gmail.com, Apr 11, 2009

I'm not sure if the "documentElement" is the best element to take as a reference since I have seen some situations where it fails while calculating the absolute position of an element. An example is when the page has CSS attributes below:

html {
margin:0;
overflow-x:hidden;
overflow-y:auto;
padding:0;
}
body {
margin:0 auto;
overflow:hidden;
padding:0;
position:relative;
width:990px;
}

Sign in to add a comment
Hosted by Google Code