tags:

views:

2203

answers:

4

Is there an efficient way to tell if a DOM element (in an HTML document) is currently visible (appears in the viewport)?

(The question regards Firefox)

A: 

Check the style.display and style.visibility properties of the DOM Element.

http://www.w3schools.com/htmldom/prop_style_display.asp

http://www.w3schools.com/HTMLDOM/prop_style_visibility.asp

Chris Pietschmann
+2  A: 

Depends what you mean by visible. If you mean is it currently shown on the page, given the scroll position, you can calculate it based on the elements y offset and the current scroll position.

roryf
+14  A: 

This will check if the element is entirely visible in the current viewport:

function elementInViewport(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top >= window.pageYOffset &&
    left >= window.pageXOffset &&
    (top + height) <= (window.pageYOffset + window.innerHeight) &&
    (left + width) <= (window.pageXOffset + window.innerWidth)
  );
}

You could modify this simply to determine if any part of the element is visible in the viewport:

function elementInViewport2(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top < (window.pageYOffset + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}
Prestaul
Original function posted had a mistake. Needed to save the width/height before reassigning el...
Prestaul
It also might be wise to abstract this a bit and create some utility functions. I use one called getViewport that returns the top/left/bottom/right of the visible window, and one called getPosition that finds the top/left of an element.
Prestaul
This is an excellent function, Thanks very much.
Neil Aitken
I'm trying to get this functionality in a Firefox extension, so just in case someone else is in the same situation... (Web developers, you can of course ignore this comment entirely) This function works perfectly in that context, EXCEPT that `window` refers to the wrong object, so just put `var window = el.ownerDocument.defaultView` at the top of the function and you're good to go.
MatrixFrog
A: 

There is jQuery plugin called inview that does the job

runner