scrollIntoView, but only if out of view

August 26th, 2009

On browsers such as Firefox, the scrollIntoView function silently returns without action if the element in question is already on the screen. However, in IE6, and perhaps other browsers, it causes the screen to scroll even if it is already in view. To workaround this, and only call the scrollIntoView function if the element in question is out of view, I wrote the following helper method — scrollIntoViewIfOutOfView.

function scrollIntoViewIfOutOfView(el) {
  var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  var elY = 0;
  var elH = 0;
  if (document.layers) { // NS4
    elY = el.y;
    elH = el.height;
  }
  else {
    for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
      elY += p.offsetTop;
    }
    elH = el.offsetHeight;
  }
  if ((topOfPage + heightOfPage) < (elY + elH)) {
    el.scrollIntoView(false);
  }
  else if (elY < topOfPage) {
    el.scrollIntoView(true);
  }
}

One Response to “scrollIntoView, but only if out of view”

  1. Hieu Le Says:

    thanks so much. This is a good solution.

Leave a Reply

Powered by WP Hashcash