-
Notifications
You must be signed in to change notification settings - Fork 34
/
sticky.js
194 lines (181 loc) · 6.25 KB
/
sticky.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/*!
* "position: sticky" polyfill
* https://github.com/matthewp/position--sticky-
* License: MIT
*/
(function () {
var prefixTestList = ['', '-webkit-', '-ms-', '-moz-', '-o-'];
var stickyTestElement = document.createElement('div');
var lastKnownScrollTop = 0;
var waitingForUpdate = false;
// requestAnimationFrame may be prefixed
var requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
for (var i = 0, l = prefixTestList.length; i < l; i++) {
stickyTestElement.style.position = prefixTestList[i] + 'sticky';
}
var slice = Array.prototype.slice;
function getBodyOffset(body) {
return {
top: body.offsetTop,
left: body.offsetLeft
};
}
function getOffset(elem) {
var docElem,
body,
win,
clientTop,
clientLeft,
scrollTop,
scrollLeft,
box = {
top: 0,
left: 0
},
doc = elem && elem.ownerDocument;
if(!doc) {
return;
}
if((body = doc.body) === elem) {
return getBodyOffset(elem);
}
docElem = doc.documentElement;
if(typeof elem.getBoundingClientRect !== "undefined") {
box = elem.getBoundingClientRect();
}
win = window;
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
}
function setStyle(elem, repl) {
var style = elem.getAttribute('style').split(';'),
newStyle = [];
for(var i = 0, l = style.length; i < l; i++) {
var both = style[i].split(':'),
key = both[0],
value = both[1];
if(key in repl) {
newStyle.push(key + ':' + repl[key]);
} else {
newStyle.push(both.join(':'));
}
}
elem.setAttribute('style', newStyle.join(';'));
}
var cssPattern = /\s*([^{}]+?)\s*{([^{}]+?)}+/g,
matchPosition = /\.*?position:.*?sticky.*?;/i,
getTop = /\.*?top:(.*?);/i,
toObserve = [];
function parse(css) {
var matches;
css = css.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm, '').replace(/\n|\r/g, '');
while((matches = cssPattern.exec(css)) !== null) {
var selector = matches[1];
if(matchPosition.test(matches[2]) && selector !== "#modernizr") {
var topMatch = getTop.exec(matches[2]),
topCSS = ((topMatch !== null) ? parseInt(topMatch[1]) : 0);
var elems = slice.call(document.querySelectorAll(selector));
matches[2] = (matches[2].trim().slice(-1) === ";") ? matches[2] : matches[2].trim() + ';';
elems.forEach(function (elem) {
var height = elem.offsetHeight,
parent = elem.parentElement,
parOff = getOffset(parent),
parOffTop = ((parOff !== null && parOff.top !== null) ? parOff.top : 0),
elmOff = getOffset(elem),
elmOffTop = ((elmOff !== null && elmOff.top !== null) ? elmOff.top : 0),
start = elmOffTop - topCSS,
end = (parOffTop + parent.offsetHeight) - height - topCSS,
newCSS = matches[2] + "position:fixed;width:100%;height:" + height + "px",
dummy = document.createElement('div');
dummy.innerHTML = '<span style="position:static;display:block;height:' + height + 'px;"></span>';
toObserve.push({
element: elem,
parent: parent,
repl: dummy.firstElementChild,
start: start,
end: end,
oldCSS: matches[2],
newCSS: newCSS,
fixed: false
});
});
}
}
}
function setPositions() {
var scrollTop = lastKnownScrollTop;
waitingForUpdate = false;
for(var i = 0, l = toObserve.length; i < l; i++) {
var obj = toObserve[i];
if(obj.fixed === false && scrollTop > obj.start && scrollTop < obj.end) {
obj.element.setAttribute('style', obj.newCSS);
obj.fixed = true;
obj.element.classList.add('stuck');
} else {
if(obj.fixed === true) {
if(scrollTop < obj.start) {
obj.element.setAttribute('style', obj.oldCSS);
obj.fixed = false;
obj.element.classList.remove('stuck');
} else {
if(scrollTop > obj.end) {
var absolute = getOffset(obj.element);
absolute.position = "absolute";
obj.element.setAttribute('style', obj.newCSS);
setStyle(obj.element, absolute);
obj.fixed = false;
obj.element.classList.remove('stuck');
}
}
}
}
}
}
// Debounced scroll handling
function updateScrollPos() {
lastKnownScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// Only trigger a layout change if we’re not already waiting for one
if (!waitingForUpdate) {
waitingForUpdate = true;
// Don’t update until next animation frame if we can, otherwise use a
// timeout - either will help avoid too many repaints
if (requestAnimationFrame) {
requestAnimationFrame(setPositions);
}
else {
setTimeout(setPositions, 15);
}
}
}
if (stickyTestElement.style.position.length === 0) { window.addEventListener('scroll', updateScrollPos); }
window.addEventListener('load', function () {
var styles = slice.call(document.querySelectorAll('style'));
styles.forEach(function (style) {
var text = style.textContent || style.innerText;
parse(text);
});
var links = slice.call(document.querySelectorAll('link'));
links.forEach(function (link) {
if(link.getAttribute('rel') !== 'stylesheet') {
return;
}
var href = link.getAttribute('href'),
req = new XMLHttpRequest();
req.open('GET', href, true);
req.onload = function (e) {
parse(req.responseText);
// Update once stylesheet loaded, in case page loaded with a scroll offset
updateScrollPos();
};
req.send();
});
}, false);
})();