-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
32 lines (26 loc) · 1.15 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var scroll = require('./scroll-to');
function calculateScrollOffset(elem, additionalOffset, alignment) {
var body = document.body,
html = document.documentElement;
var elemRect = elem.getBoundingClientRect();
var clientHeight = html.clientHeight;
var documentHeight = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
additionalOffset = additionalOffset || 0;
var scrollPosition;
if (alignment === 'bottom') {
scrollPosition = elemRect.bottom - clientHeight;
} else if (alignment === 'middle') {
scrollPosition = elemRect.bottom - clientHeight / 2 - elemRect.height / 2;
} else { // top and default
scrollPosition = elemRect.top;
}
var maxScrollPosition = documentHeight - clientHeight;
return Math.min(scrollPosition + additionalOffset + window.pageYOffset,
maxScrollPosition);
}
module.exports = function (elem, options) {
options = options || {};
if (typeof elem === 'string') elem = document.querySelector(elem);
if (elem) return scroll(0, calculateScrollOffset(elem, options.offset, options.align), options);
};