Skip to content

Instantly share code, notes, and snippets.

@kbtz
Last active March 14, 2017 02:37
Show Gist options
  • Save kbtz/cbff8bf047e9eae822a6ae89dd53ee71 to your computer and use it in GitHub Desktop.
Save kbtz/cbff8bf047e9eae822a6ae89dd53ee71 to your computer and use it in GitHub Desktop.
Makes sure a given element is in the visible area of its scroll container;
function ensureVisibility(e, c) {
let e0 = e.offsetTop
let eD = e.clientHeight
let e1 = e0 + eD
let c0 = c.scrollTop
let cD = c.clientHeight
let c1 = c0 + cD
let visible = e0 > c0 && e1 < c1
if (!visible) {
if (e0 <= c0) {
// Stick at container top
c.scrollTop = e0
} else {
// Stick at container bottom
c.scrollTop = e1 - cD
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment