Created
March 22, 2018 20:23
-
-
Save KurtPreston/1859266b6ca56092858550f0fe3e8537 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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