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); } }
June 10th, 2010 at 10:13 am
thanks so much. This is a good solution.