forked from willhoag/scroll-to-element
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (56 loc) · 2.52 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 contentHeight = 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 = contentHeight - clientHeight;
return Math.min(scrollPosition + additionalOffset + window.pageYOffset, maxScrollPosition);
}
function calculateScrollOffsetContainer(elem, additionalOffset, alignment, container, content) {
var elemRect = elem.getBoundingClientRect();
var containerRect = container.getBoundingClientRect();
var containerHeight = containerRect.height;
var contentHeight = Math.max( content.scrollHeight, content.offsetHeight,
containerHeight, container.scrollHeight, container.offsetHeight );
additionalOffset = additionalOffset || 0;
var scrollPosition;
if (alignment === 'bottom') {
scrollPosition = elemRect.bottom - containerRect.bottom;
} else if (alignment === 'middle') {
scrollPosition = elemRect.bottom - (containerRect.bottom - (containerHeight / 2)) + (elemRect.height / 2);
} else { // top and default
scrollPosition = elemRect.top - containerRect.top;
}
var maxScrollPosition = contentHeight - containerHeight;
return Math.min(scrollPosition + additionalOffset + container.scrollTop, maxScrollPosition);
}
module.exports = function (elem, options, container, content, onEnd) {
options = options || {};
if (typeof elem === 'string') {
elem = document.querySelector(elem);
if (!container) {
var scrollY = calculateScrollOffset(elem, options.offset, options.align);
return scroll(0, scrollY, options, undefined, onEnd);
}
if (typeof container === 'string' && typeof content === 'string') {
container = document.querySelector(container);
content = document.querySelector(content);
if (container && content) {
var scrollY = calculateScrollOffsetContainer(elem, options.offset, options.align, container, content);
return scroll(0, scrollY, options, container, onEnd);
}
}
}
};