Skip to content

Instantly share code, notes, and snippets.

@harmoniemand
Last active June 26, 2018 15:49
Show Gist options
  • Save harmoniemand/35b56895a14be1bf1727ff81f5206757 to your computer and use it in GitHub Desktop.
Save harmoniemand/35b56895a14be1bf1727ff81f5206757 to your computer and use it in GitHub Desktop.
Calculate Offset in HTML while using offset and scrolling
/*
License: MIT (https://opensource.org/licenses/MIT)
*/
GetOffset(from: any, to: any): PositionModel {
let pos = new PositionModel();
var parent = from.offsetParent;
pos.X = from.offsetTop;
pos.Y = from.offsetLeft;
var el = from;
while (el != parent) {
pos.X = pos.X - el.scrollTop;
pos.Y = pos.Y - el.scrollLeft;
el = el.parentNode;
}
if (parent != to) {
const parentOffset = this.GetOffset(parent, to);
pos.X = pos.X + parentOffset.X;
pos.Y = pos.Y + parentOffset.Y;
}
return pos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment