Skip to content

Instantly share code, notes, and snippets.

@KurtPreston
Created March 22, 2018 20:23
Show Gist options
  • Save KurtPreston/1859266b6ca56092858550f0fe3e8537 to your computer and use it in GitHub Desktop.
Save KurtPreston/1859266b6ca56092858550f0fe3e8537 to your computer and use it in GitHub Desktop.
export function scrollToCenter(target: HTMLElement, container: HTMLElement): void {
// Vertically center element in container
container.scrollTop = verticalOffset(target, container) - (container.offsetHeight - target.offsetHeight) / 2;
}
function verticalOffset(target: HTMLElement, container: HTMLElement): number {
const commonAncestor = commonContainer(target, container);
const parent: HTMLElement = target.offsetParent as any;
if(parent === commonAncestor) {
return target.offsetTop;
} else {
return target.offsetTop + verticalOffset(parent, container);
}
}
function commonContainer(a: HTMLElement, b: HTMLElement): HTMLElement {
const aHierarchy = offsetHierarchy(a);
const bHierarchy = offsetHierarchy(b);
const commonParent = aHierarchy.find((el) => bHierarchy.indexOf(el) >= 0);
return commonParent;
}
function offsetHierarchy(target: HTMLElement): HTMLElement[] {
const parent: HTMLElement = target.offsetParent as any;
if (parent) {
return [
target,
...offsetHierarchy(parent)
];
} else {
return [
target
]
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment