To get an elements offset I use:
function(el) {
if(el && el.parentNode) {
var x = 0;
var y = 0;
while(el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
return {x: x, y: y};
}
return null;
}
and to get its scroll offset I use:
function(el) {
if(el && el.parentNode) {
var x = 0;
var y = 0;
while(el) {
if(el && el.parentNode) {
x += el.scrollLeft;
y += el.scrollTop;
el = el.parentNode;
} else {
el = null;
}
}
return {x: x, y: y};
}
return null;
}
Problem is I can’t figure out how to merge these two functions together so I can get an elements offset including any scrolling thats been done on the page. When setting an elements position I usually just have to reference both functions, but it seems like it makes sense to just get the total offset in one function. How can I achieve this? Is it event a good idea to do this all in one function, or are there specific use cases when it would be a good idea to get the offset without the scroll?
You mean something like this?