diff --git a/.gitignore b/.gitignore index 5e4b775..3809511 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ node_modules *.log maps +.idea diff --git a/README.md b/README.md index 78c03bc..6a508d1 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ jump('.target', { duration: 1000, offset: 0, callback: undefined, + container: window, easing: easeInOutQuad, a11y: false }) @@ -67,6 +68,7 @@ Explanation of each option follows: * [duration](#duration) * [offset](#offset) * [callback](#callback) +* [container](#container) * [easing](#easing) * [a11y](#a11y) @@ -152,6 +154,17 @@ jump('.target', { }) ``` +### container + +Pass a custom container element instead of scrolling `window`. The option +`container` can be a CSS selector or a node. + +```es6 +jump('.target', { + container: '#myScrollableContainer' +}) +``` + ### easing Easing function used to transition the `jump()`. diff --git a/src/jump.js b/src/jump.js index 9e59114..ff85e61 100644 --- a/src/jump.js +++ b/src/jump.js @@ -4,6 +4,7 @@ const jumper = () => { // private variable cache // no variables are created during a jump, preventing memory leaks + let container // container element to be scrolled (node) let element // element to scroll to (node) let start // where scroll starts (px) @@ -26,13 +27,26 @@ const jumper = () => { // scroll position helper function location() { - return window.scrollY || window.pageYOffset + return container.scrollY || container.pageYOffset || container.scrollTop } // element offset helper function top(element) { - return element.getBoundingClientRect().top + start + const elementTop = element.getBoundingClientRect().top + const containerTop = container.getBoundingClientRect + ? container.getBoundingClientRect().top + : 0 + + return elementTop - containerTop + start + } + + // scrollTo helper + + function scrollTo(top) { + container.scrollTo + ? container.scrollTo(0, top) // window + : container.scrollTop = top // custom container } // rAF loop helper @@ -50,7 +64,7 @@ const jumper = () => { next = easing(timeElapsed, start, distance, duration) // scroll to it - window.scrollTo(0, next) + scrollTo(next) // check progress timeElapsed < duration @@ -62,7 +76,7 @@ const jumper = () => { function done() { // account for rAF time rounding inaccuracies - window.scrollTo(0, start + distance) + scrollTo(start + distance) // if scrolling to an element, and accessibility is enabled if(element && a11y) { @@ -92,6 +106,21 @@ const jumper = () => { easing = options.easing || easeInOutQuad a11y = options.a11y || false + // resolve container + switch(typeof options.container) { + case 'object': + // we assume container is an HTML element (Node) + container = options.container + break + + case 'string': + container = document.querySelector(options.container) + break + + default: + container = window + } + // cache starting position start = location()