Skip to content

Instantly share code, notes, and snippets.

@premasagar
Created September 19, 2012 21:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save premasagar/3752365 to your computer and use it in GitHub Desktop.
Save premasagar/3752365 to your computer and use it in GitHub Desktop.
// e.g. scrollToTarget(document.getElementById('foo'));
function offset(target){
var left = 0,
top = 0;
while (target && target !== document.body){
if (target.offsetLeft){
left += target.offsetLeft;
top += target.offsetTop;
}
target = target.offsetParent;
}
return {left:left, top:top};
}
function scrollToTarget(target){
var pos = offset(target);
window.scrollTo(pos.left, pos.top);
return pos;
}
// e.g. scrollToY(document.getElementById('foo'));
function offsetY(target){
var top = 0;
while (target && target !== document.body){
if (target.offsetTop){
top += target.offsetTop;
}
target = target.offsetParent;
}
return top;
}
function scrollToY(target){
var top = offsetY(target);
window.scrollTo(window.scrollX, top);
return top;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment