stickyfill.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /*!
  2. * Stickyfill – `position: sticky` polyfill
  3. * v. 2.1.0 | https://github.com/wilddeer/stickyfill
  4. * MIT License
  5. */
  6. ;(function(window, document) {
  7. 'use strict';
  8. /*
  9. * 1. Check if the browser supports `position: sticky` natively or is too old to run the polyfill.
  10. * If either of these is the case set `seppuku` flag. It will be checked later to disable key features
  11. * of the polyfill, but the API will remain functional to avoid breaking things.
  12. */
  13. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  14. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  15. var seppuku = false;
  16. var isWindowDefined = typeof window !== 'undefined';
  17. // The polyfill can’t function properly without `window` or `window.getComputedStyle`.
  18. if (!isWindowDefined || !window.getComputedStyle) seppuku = true;
  19. // Dont’t get in a way if the browser supports `position: sticky` natively.
  20. else {
  21. (function () {
  22. var testNode = document.createElement('div');
  23. if (['', '-webkit-', '-moz-', '-ms-'].some(function (prefix) {
  24. try {
  25. testNode.style.position = prefix + 'sticky';
  26. } catch (e) {}
  27. return testNode.style.position != '';
  28. })) seppuku = true;
  29. })();
  30. }
  31. /*
  32. * 2. “Global” vars used across the polyfill
  33. */
  34. var isInitialized = false;
  35. // Check if Shadow Root constructor exists to make further checks simpler
  36. var shadowRootExists = typeof ShadowRoot !== 'undefined';
  37. // Last saved scroll position
  38. var scroll = {
  39. top: null,
  40. left: null
  41. };
  42. // Array of created Sticky instances
  43. var stickies = [];
  44. /*
  45. * 3. Utility functions
  46. */
  47. function extend(targetObj, sourceObject) {
  48. for (var key in sourceObject) {
  49. if (sourceObject.hasOwnProperty(key)) {
  50. targetObj[key] = sourceObject[key];
  51. }
  52. }
  53. }
  54. function parseNumeric(val) {
  55. return parseFloat(val) || 0;
  56. }
  57. function getDocOffsetTop(node) {
  58. var docOffsetTop = 0;
  59. while (node) {
  60. docOffsetTop += node.offsetTop;
  61. node = node.offsetParent;
  62. }
  63. return docOffsetTop;
  64. }
  65. /*
  66. * 4. Sticky class
  67. */
  68. var Sticky = function () {
  69. function Sticky(node) {
  70. _classCallCheck(this, Sticky);
  71. if (!(node instanceof HTMLElement)) throw new Error('First argument must be HTMLElement');
  72. if (stickies.some(function (sticky) {
  73. return sticky._node === node;
  74. })) throw new Error('Stickyfill is already applied to this node');
  75. this._node = node;
  76. this._stickyMode = null;
  77. this._active = false;
  78. stickies.push(this);
  79. this.refresh();
  80. }
  81. _createClass(Sticky, [{
  82. key: 'refresh',
  83. value: function refresh() {
  84. if (seppuku || this._removed) return;
  85. if (this._active) this._deactivate();
  86. var node = this._node;
  87. /*
  88. * 1. Save node computed props
  89. */
  90. var nodeComputedStyle = getComputedStyle(node);
  91. var nodeComputedProps = {
  92. position: nodeComputedStyle.position,
  93. top: nodeComputedStyle.top,
  94. display: nodeComputedStyle.display,
  95. marginTop: nodeComputedStyle.marginTop,
  96. marginBottom: nodeComputedStyle.marginBottom,
  97. marginLeft: nodeComputedStyle.marginLeft,
  98. marginRight: nodeComputedStyle.marginRight,
  99. cssFloat: nodeComputedStyle.cssFloat
  100. };
  101. /*
  102. * 2. Check if the node can be activated
  103. */
  104. if (isNaN(parseFloat(nodeComputedProps.top)) || nodeComputedProps.display == 'table-cell' || nodeComputedProps.display == 'none') return;
  105. this._active = true;
  106. /*
  107. * 3. Check if the current node position is `sticky`. If it is, it means that the browser supports sticky positioning,
  108. * but the polyfill was force-enabled. We set the node’s position to `static` before continuing, so that the node
  109. * is in it’s initial position when we gather its params.
  110. */
  111. var originalPosition = node.style.position;
  112. if (nodeComputedStyle.position == 'sticky' || nodeComputedStyle.position == '-webkit-sticky') node.style.position = 'static';
  113. /*
  114. * 4. Get necessary node parameters
  115. */
  116. var referenceNode = node.parentNode;
  117. var parentNode = shadowRootExists && referenceNode instanceof ShadowRoot ? referenceNode.host : referenceNode;
  118. var nodeWinOffset = node.getBoundingClientRect();
  119. var parentWinOffset = parentNode.getBoundingClientRect();
  120. var parentComputedStyle = getComputedStyle(parentNode);
  121. this._parent = {
  122. node: parentNode,
  123. styles: {
  124. position: parentNode.style.position
  125. },
  126. offsetHeight: parentNode.offsetHeight
  127. };
  128. this._offsetToWindow = {
  129. left: nodeWinOffset.left,
  130. right: document.documentElement.clientWidth - nodeWinOffset.right
  131. };
  132. this._offsetToParent = {
  133. top: nodeWinOffset.top - parentWinOffset.top - parseNumeric(parentComputedStyle.borderTopWidth),
  134. left: nodeWinOffset.left - parentWinOffset.left - parseNumeric(parentComputedStyle.borderLeftWidth),
  135. right: -nodeWinOffset.right + parentWinOffset.right - parseNumeric(parentComputedStyle.borderRightWidth)
  136. };
  137. this._styles = {
  138. position: originalPosition,
  139. top: node.style.top,
  140. bottom: node.style.bottom,
  141. left: node.style.left,
  142. right: node.style.right,
  143. width: node.style.width,
  144. marginTop: node.style.marginTop,
  145. marginLeft: node.style.marginLeft,
  146. marginRight: node.style.marginRight
  147. };
  148. var nodeTopValue = parseNumeric(nodeComputedProps.top);
  149. this._limits = {
  150. start: nodeWinOffset.top + window.pageYOffset - nodeTopValue,
  151. end: parentWinOffset.top + window.pageYOffset + parentNode.offsetHeight - parseNumeric(parentComputedStyle.borderBottomWidth) - node.offsetHeight - nodeTopValue - parseNumeric(nodeComputedProps.marginBottom)
  152. };
  153. /*
  154. * 5. Ensure that the node will be positioned relatively to the parent node
  155. */
  156. var parentPosition = parentComputedStyle.position;
  157. if (parentPosition != 'absolute' && parentPosition != 'relative') {
  158. parentNode.style.position = 'relative';
  159. }
  160. /*
  161. * 6. Recalc node position.
  162. * It’s important to do this before clone injection to avoid scrolling bug in Chrome.
  163. */
  164. this._recalcPosition();
  165. /*
  166. * 7. Create a clone
  167. */
  168. var clone = this._clone = {};
  169. clone.node = document.createElement('div');
  170. // Apply styles to the clone
  171. extend(clone.node.style, {
  172. width: nodeWinOffset.right - nodeWinOffset.left + 'px',
  173. height: nodeWinOffset.bottom - nodeWinOffset.top + 'px',
  174. marginTop: nodeComputedProps.marginTop,
  175. marginBottom: nodeComputedProps.marginBottom,
  176. marginLeft: nodeComputedProps.marginLeft,
  177. marginRight: nodeComputedProps.marginRight,
  178. cssFloat: nodeComputedProps.cssFloat,
  179. padding: 0,
  180. border: 0,
  181. borderSpacing: 0,
  182. fontSize: '1em',
  183. position: 'static'
  184. });
  185. referenceNode.insertBefore(clone.node, node);
  186. clone.docOffsetTop = getDocOffsetTop(clone.node);
  187. }
  188. }, {
  189. key: '_recalcPosition',
  190. value: function _recalcPosition() {
  191. if (!this._active || this._removed) return;
  192. var stickyMode = scroll.top <= this._limits.start ? 'start' : scroll.top >= this._limits.end ? 'end' : 'middle';
  193. if (this._stickyMode == stickyMode) return;
  194. switch (stickyMode) {
  195. case 'start':
  196. extend(this._node.style, {
  197. position: 'absolute',
  198. left: this._offsetToParent.left + 'px',
  199. right: this._offsetToParent.right + 'px',
  200. top: this._offsetToParent.top + 'px',
  201. bottom: 'auto',
  202. width: 'auto',
  203. marginLeft: 0,
  204. marginRight: 0,
  205. marginTop: 0
  206. });
  207. break;
  208. case 'middle':
  209. extend(this._node.style, {
  210. position: 'fixed',
  211. left: this._offsetToWindow.left + 'px',
  212. right: this._offsetToWindow.right + 'px',
  213. top: this._styles.top,
  214. bottom: 'auto',
  215. width: 'auto',
  216. marginLeft: 0,
  217. marginRight: 0,
  218. marginTop: 0
  219. });
  220. break;
  221. case 'end':
  222. extend(this._node.style, {
  223. position: 'absolute',
  224. left: this._offsetToParent.left + 'px',
  225. right: this._offsetToParent.right + 'px',
  226. top: 'auto',
  227. bottom: 0,
  228. width: 'auto',
  229. marginLeft: 0,
  230. marginRight: 0
  231. });
  232. break;
  233. }
  234. this._stickyMode = stickyMode;
  235. }
  236. }, {
  237. key: '_fastCheck',
  238. value: function _fastCheck() {
  239. if (!this._active || this._removed) return;
  240. if (Math.abs(getDocOffsetTop(this._clone.node) - this._clone.docOffsetTop) > 1 || Math.abs(this._parent.node.offsetHeight - this._parent.offsetHeight) > 1) this.refresh();
  241. }
  242. }, {
  243. key: '_deactivate',
  244. value: function _deactivate() {
  245. var _this = this;
  246. if (!this._active || this._removed) return;
  247. this._clone.node.parentNode.removeChild(this._clone.node);
  248. delete this._clone;
  249. extend(this._node.style, this._styles);
  250. delete this._styles;
  251. // Check whether element’s parent node is used by other stickies.
  252. // If not, restore parent node’s styles.
  253. if (!stickies.some(function (sticky) {
  254. return sticky !== _this && sticky._parent && sticky._parent.node === _this._parent.node;
  255. })) {
  256. extend(this._parent.node.style, this._parent.styles);
  257. }
  258. delete this._parent;
  259. this._stickyMode = null;
  260. this._active = false;
  261. delete this._offsetToWindow;
  262. delete this._offsetToParent;
  263. delete this._limits;
  264. }
  265. }, {
  266. key: 'remove',
  267. value: function remove() {
  268. var _this2 = this;
  269. this._deactivate();
  270. stickies.some(function (sticky, index) {
  271. if (sticky._node === _this2._node) {
  272. stickies.splice(index, 1);
  273. return true;
  274. }
  275. });
  276. this._removed = true;
  277. }
  278. }]);
  279. return Sticky;
  280. }();
  281. /*
  282. * 5. Stickyfill API
  283. */
  284. var Stickyfill = {
  285. stickies: stickies,
  286. Sticky: Sticky,
  287. forceSticky: function forceSticky() {
  288. seppuku = false;
  289. init();
  290. this.refreshAll();
  291. },
  292. addOne: function addOne(node) {
  293. // Check whether it’s a node
  294. if (!(node instanceof HTMLElement)) {
  295. // Maybe it’s a node list of some sort?
  296. // Take first node from the list then
  297. if (node.length && node[0]) node = node[0];else return;
  298. }
  299. // Check if Stickyfill is already applied to the node
  300. // and return existing sticky
  301. for (var i = 0; i < stickies.length; i++) {
  302. if (stickies[i]._node === node) return stickies[i];
  303. }
  304. // Create and return new sticky
  305. return new Sticky(node);
  306. },
  307. add: function add(nodeList) {
  308. // If it’s a node make an array of one node
  309. if (nodeList instanceof HTMLElement) nodeList = [nodeList];
  310. // Check if the argument is an iterable of some sort
  311. if (!nodeList.length) return;
  312. // Add every element as a sticky and return an array of created Sticky instances
  313. var addedStickies = [];
  314. var _loop = function _loop(i) {
  315. var node = nodeList[i];
  316. // If it’s not an HTMLElement – create an empty element to preserve 1-to-1
  317. // correlation with input list
  318. if (!(node instanceof HTMLElement)) {
  319. addedStickies.push(void 0);
  320. return 'continue';
  321. }
  322. // If Stickyfill is already applied to the node
  323. // add existing sticky
  324. if (stickies.some(function (sticky) {
  325. if (sticky._node === node) {
  326. addedStickies.push(sticky);
  327. return true;
  328. }
  329. })) return 'continue';
  330. // Create and add new sticky
  331. addedStickies.push(new Sticky(node));
  332. };
  333. for (var i = 0; i < nodeList.length; i++) {
  334. var _ret2 = _loop(i);
  335. if (_ret2 === 'continue') continue;
  336. }
  337. return addedStickies;
  338. },
  339. refreshAll: function refreshAll() {
  340. stickies.forEach(function (sticky) {
  341. return sticky.refresh();
  342. });
  343. },
  344. removeOne: function removeOne(node) {
  345. // Check whether it’s a node
  346. if (!(node instanceof HTMLElement)) {
  347. // Maybe it’s a node list of some sort?
  348. // Take first node from the list then
  349. if (node.length && node[0]) node = node[0];else return;
  350. }
  351. // Remove the stickies bound to the nodes in the list
  352. stickies.some(function (sticky) {
  353. if (sticky._node === node) {
  354. sticky.remove();
  355. return true;
  356. }
  357. });
  358. },
  359. remove: function remove(nodeList) {
  360. // If it’s a node make an array of one node
  361. if (nodeList instanceof HTMLElement) nodeList = [nodeList];
  362. // Check if the argument is an iterable of some sort
  363. if (!nodeList.length) return;
  364. // Remove the stickies bound to the nodes in the list
  365. var _loop2 = function _loop2(i) {
  366. var node = nodeList[i];
  367. stickies.some(function (sticky) {
  368. if (sticky._node === node) {
  369. sticky.remove();
  370. return true;
  371. }
  372. });
  373. };
  374. for (var i = 0; i < nodeList.length; i++) {
  375. _loop2(i);
  376. }
  377. },
  378. removeAll: function removeAll() {
  379. while (stickies.length) {
  380. stickies[0].remove();
  381. }
  382. }
  383. };
  384. /*
  385. * 6. Setup events (unless the polyfill was disabled)
  386. */
  387. function init() {
  388. if (isInitialized) {
  389. return;
  390. }
  391. isInitialized = true;
  392. // Watch for scroll position changes and trigger recalc/refresh if needed
  393. function checkScroll() {
  394. if (window.pageXOffset != scroll.left) {
  395. scroll.top = window.pageYOffset;
  396. scroll.left = window.pageXOffset;
  397. Stickyfill.refreshAll();
  398. } else if (window.pageYOffset != scroll.top) {
  399. scroll.top = window.pageYOffset;
  400. scroll.left = window.pageXOffset;
  401. // recalc position for all stickies
  402. stickies.forEach(function (sticky) {
  403. return sticky._recalcPosition();
  404. });
  405. }
  406. }
  407. checkScroll();
  408. window.addEventListener('scroll', checkScroll);
  409. // Watch for window resizes and device orientation changes and trigger refresh
  410. window.addEventListener('resize', Stickyfill.refreshAll);
  411. window.addEventListener('orientationchange', Stickyfill.refreshAll);
  412. //Fast dirty check for layout changes every 500ms
  413. var fastCheckTimer = void 0;
  414. function startFastCheckTimer() {
  415. fastCheckTimer = setInterval(function () {
  416. stickies.forEach(function (sticky) {
  417. return sticky._fastCheck();
  418. });
  419. }, 500);
  420. }
  421. function stopFastCheckTimer() {
  422. clearInterval(fastCheckTimer);
  423. }
  424. var docHiddenKey = void 0;
  425. var visibilityChangeEventName = void 0;
  426. if ('hidden' in document) {
  427. docHiddenKey = 'hidden';
  428. visibilityChangeEventName = 'visibilitychange';
  429. } else if ('webkitHidden' in document) {
  430. docHiddenKey = 'webkitHidden';
  431. visibilityChangeEventName = 'webkitvisibilitychange';
  432. }
  433. if (visibilityChangeEventName) {
  434. if (!document[docHiddenKey]) startFastCheckTimer();
  435. document.addEventListener(visibilityChangeEventName, function () {
  436. if (document[docHiddenKey]) {
  437. stopFastCheckTimer();
  438. } else {
  439. startFastCheckTimer();
  440. }
  441. });
  442. } else startFastCheckTimer();
  443. }
  444. if (!seppuku) init();
  445. /*
  446. * 7. Expose Stickyfill
  447. */
  448. if (typeof module != 'undefined' && module.exports) {
  449. module.exports = Stickyfill;
  450. } else if (isWindowDefined) {
  451. window.Stickyfill = Stickyfill;
  452. }
  453. })(window, document);