Skip to content

Instantly share code, notes, and snippets.

@jmshal
Created October 6, 2016 09:54
Show Gist options
  • Save jmshal/53c856c340000421fd7d9fc794b23086 to your computer and use it in GitHub Desktop.
Save jmshal/53c856c340000421fd7d9fc794b23086 to your computer and use it in GitHub Desktop.
npm i --save gist:53c856c340000421fd7d9fc794b23086
'use strict';
const TEST_OVERFLOW = /(auto|scroll)/;
/**
* Scrolls to an element by scrolling it's parent scroll container.
*
* @param {Element} element The element to scroll to
* @param {boolean} [center] Whether to center the element within it's scroll container
*/
function scrollTo(element, center = false) {
if (element.length) {
if (element.length > 1) {
console.warn('Multiple elements passed to scrollTo, only scrolling the first.');
}
element = element[0];
}
let scrollContainer = null;
let parentElement = element;
const position = getComputedStyle(element)['position'];
const document = element.ownerDocument;
if (position === 'fixed') {
scrollContainer = document;
} else {
const excludeStatic = position === 'absolute';
while ((parentElement = parentElement.parentElement) !== null) {
const style = getComputedStyle(parentElement);
if (excludeStatic && style['position'] === 'static') {
continue;
}
const overflow = style['overflow'] + style['overflow-y'] + style['overflow-x'];
if (TEST_OVERFLOW.test(overflow)) {
scrollContainer = parentElement;
break;
}
}
}
if (!scrollContainer) {
console.warn('Unable to find scroll container.');
return;
}
const documentElement = document.documentElement;
const clientRect = element.getBoundingClientRect();
let top = clientRect.top + window.pageYOffset - documentElement.clientTop;
let left = clientRect.left + window.pageXOffset - documentElement.clientLeft;
if (center) {
const containerClientRect = scrollContainer.getBoundingClientRect();
top += -(containerClientRect.height / 2) + (clientRect.height / 2);
left += -(containerClientRect.width / 2) + (clientRect.width / 2);
}
scrollContainer.scrollTop += top;
scrollContainer.scrollLeft += left;
}
module.exports = scrollTo;
{
"name": "scroll-to",
"version": "1.0.0",
"description": "A simple commonjs function which scrolls an element into view."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment