Skip to content

Instantly share code, notes, and snippets.

@maskingtape
Forked from premasagar/scroll-to-target.js
Created September 20, 2012 14:02
Show Gist options
  • Save maskingtape/3756117 to your computer and use it in GitHub Desktop.
Save maskingtape/3756117 to your computer and use it in GitHub Desktop.
// e.g. scrollToTarget(document.getElementById('foo'));
function getOffset(target){
var offset = {};
function getOrdinate(offsetType){
var ord = 0;
while (target && target !== document.body){
if (target[offsetType]){
ord += target[offsetType];
}
target = target.offsetParent;
}
return ord;
}
offset.top = getOrdinate('offsetTop');
offset.left = getOrdinate('offsetLeft');
return offset;
}
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