You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

645 lines
19 KiB

5 years ago
  1. /*!
  2. * smooth-scroll v16.1.0
  3. * Animate scrolling to anchor links
  4. * (c) 2019 Chris Ferdinandi
  5. * MIT License
  6. * http://github.com/cferdinandi/smooth-scroll
  7. */
  8. (function (root, factory) {
  9. if (typeof define === 'function' && define.amd) {
  10. define([], (function () {
  11. return factory(root);
  12. }));
  13. } else if (typeof exports === 'object') {
  14. module.exports = factory(root);
  15. } else {
  16. root.SmoothScroll = factory(root);
  17. }
  18. })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
  19. 'use strict';
  20. //
  21. // Default settings
  22. //
  23. var defaults = {
  24. // Selectors
  25. ignore: '[data-scroll-ignore]',
  26. header: null,
  27. topOnEmptyHash: true,
  28. // Speed & Duration
  29. speed: 500,
  30. speedAsDuration: false,
  31. durationMax: null,
  32. durationMin: null,
  33. clip: true,
  34. offset: 0,
  35. // Easing
  36. easing: 'easeInOutCubic',
  37. customEasing: null,
  38. // History
  39. updateURL: true,
  40. popstate: true,
  41. // Custom Events
  42. emitEvents: true
  43. };
  44. //
  45. // Utility Methods
  46. //
  47. /**
  48. * Check if browser supports required methods
  49. * @return {Boolean} Returns true if all required methods are supported
  50. */
  51. var supports = function () {
  52. return (
  53. 'querySelector' in document &&
  54. 'addEventListener' in window &&
  55. 'requestAnimationFrame' in window &&
  56. 'closest' in window.Element.prototype
  57. );
  58. };
  59. /**
  60. * Merge two or more objects together.
  61. * @param {Object} objects The objects to merge together
  62. * @returns {Object} Merged values of defaults and options
  63. */
  64. var extend = function () {
  65. var merged = {};
  66. Array.prototype.forEach.call(arguments, (function (obj) {
  67. for (var key in obj) {
  68. if (!obj.hasOwnProperty(key)) return;
  69. merged[key] = obj[key];
  70. }
  71. }));
  72. return merged;
  73. };
  74. /**
  75. * Check to see if user prefers reduced motion
  76. * @param {Object} settings Script settings
  77. */
  78. var reduceMotion = function () {
  79. if ('matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches) {
  80. return true;
  81. }
  82. return false;
  83. };
  84. /**
  85. * Get the height of an element.
  86. * @param {Node} elem The element to get the height of
  87. * @return {Number} The element's height in pixels
  88. */
  89. var getHeight = function (elem) {
  90. return parseInt(window.getComputedStyle(elem).height, 10);
  91. };
  92. /**
  93. * Escape special characters for use with querySelector
  94. * @author Mathias Bynens
  95. * @link https://github.com/mathiasbynens/CSS.escape
  96. * @param {String} id The anchor ID to escape
  97. */
  98. var escapeCharacters = function (id) {
  99. // Remove leading hash
  100. if (id.charAt(0) === '#') {
  101. id = id.substr(1);
  102. }
  103. var string = String(id);
  104. var length = string.length;
  105. var index = -1;
  106. var codeUnit;
  107. var result = '';
  108. var firstCodeUnit = string.charCodeAt(0);
  109. while (++index < length) {
  110. codeUnit = string.charCodeAt(index);
  111. // Note: there’s no need to special-case astral symbols, surrogate
  112. // pairs, or lone surrogates.
  113. // If the character is NULL (U+0000), then throw an
  114. // `InvalidCharacterError` exception and terminate these steps.
  115. if (codeUnit === 0x0000) {
  116. throw new InvalidCharacterError(
  117. 'Invalid character: the input contains U+0000.'
  118. );
  119. }
  120. if (
  121. // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
  122. // U+007F, […]
  123. (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F ||
  124. // If the character is the first character and is in the range [0-9]
  125. // (U+0030 to U+0039), […]
  126. (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
  127. // If the character is the second character and is in the range [0-9]
  128. // (U+0030 to U+0039) and the first character is a `-` (U+002D), […]
  129. (
  130. index === 1 &&
  131. codeUnit >= 0x0030 && codeUnit <= 0x0039 &&
  132. firstCodeUnit === 0x002D
  133. )
  134. ) {
  135. // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point
  136. result += '\\' + codeUnit.toString(16) + ' ';
  137. continue;
  138. }
  139. // If the character is not handled by one of the above rules and is
  140. // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or
  141. // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to
  142. // U+005A), or [a-z] (U+0061 to U+007A), […]
  143. if (
  144. codeUnit >= 0x0080 ||
  145. codeUnit === 0x002D ||
  146. codeUnit === 0x005F ||
  147. codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
  148. codeUnit >= 0x0041 && codeUnit <= 0x005A ||
  149. codeUnit >= 0x0061 && codeUnit <= 0x007A
  150. ) {
  151. // the character itself
  152. result += string.charAt(index);
  153. continue;
  154. }
  155. // Otherwise, the escaped character.
  156. // http://dev.w3.org/csswg/cssom/#escape-a-character
  157. result += '\\' + string.charAt(index);
  158. }
  159. // Return sanitized hash
  160. return '#' + result;
  161. };
  162. /**
  163. * Calculate the easing pattern
  164. * @link https://gist.github.com/gre/1650294
  165. * @param {String} type Easing pattern
  166. * @param {Number} time Time animation should take to complete
  167. * @returns {Number}
  168. */
  169. var easingPattern = function (settings, time) {
  170. var pattern;
  171. // Default Easing Patterns
  172. if (settings.easing === 'easeInQuad') pattern = time * time; // accelerating from zero velocity
  173. if (settings.easing === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity
  174. if (settings.easing === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
  175. if (settings.easing === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity
  176. if (settings.easing === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity
  177. if (settings.easing === 'easeInOutCubic') pattern = time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
  178. if (settings.easing === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity
  179. if (settings.easing === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity
  180. if (settings.easing === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
  181. if (settings.easing === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity
  182. if (settings.easing === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity
  183. if (settings.easing === 'easeInOutQuint') pattern = time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
  184. // Custom Easing Patterns
  185. if (!!settings.customEasing) pattern = settings.customEasing(time);
  186. return pattern || time; // no easing, no acceleration
  187. };
  188. /**
  189. * Determine the document's height
  190. * @returns {Number}
  191. */
  192. var getDocumentHeight = function () {
  193. return Math.max(
  194. document.body.scrollHeight, document.documentElement.scrollHeight,
  195. document.body.offsetHeight, document.documentElement.offsetHeight,
  196. document.body.clientHeight, document.documentElement.clientHeight
  197. );
  198. };
  199. /**
  200. * Calculate how far to scroll
  201. * Clip support added by robjtede - https://github.com/cferdinandi/smooth-scroll/issues/405
  202. * @param {Element} anchor The anchor element to scroll to
  203. * @param {Number} headerHeight Height of a fixed header, if any
  204. * @param {Number} offset Number of pixels by which to offset scroll
  205. * @param {Boolean} clip If true, adjust scroll distance to prevent abrupt stops near the bottom of the page
  206. * @returns {Number}
  207. */
  208. var getEndLocation = function (anchor, headerHeight, offset, clip) {
  209. var location = 0;
  210. if (anchor.offsetParent) {
  211. do {
  212. location += anchor.offsetTop;
  213. anchor = anchor.offsetParent;
  214. } while (anchor);
  215. }
  216. location = Math.max(location - headerHeight - offset, 0);
  217. if (clip) {
  218. location = Math.min(location, getDocumentHeight() - window.innerHeight);
  219. }
  220. return location;
  221. };
  222. /**
  223. * Get the height of the fixed header
  224. * @param {Node} header The header
  225. * @return {Number} The height of the header
  226. */
  227. var getHeaderHeight = function (header) {
  228. return !header ? 0 : (getHeight(header) + header.offsetTop);
  229. };
  230. /**
  231. * Calculate the speed to use for the animation
  232. * @param {Number} distance The distance to travel
  233. * @param {Object} settings The plugin settings
  234. * @return {Number} How fast to animate
  235. */
  236. var getSpeed = function (distance, settings) {
  237. var speed = settings.speedAsDuration ? settings.speed : Math.abs(distance / 1000 * settings.speed);
  238. if (settings.durationMax && speed > settings.durationMax) return settings.durationMax;
  239. if (settings.durationMin && speed < settings.durationMin) return settings.durationMin;
  240. return parseInt(speed, 10);
  241. };
  242. var setHistory = function (options) {
  243. // Make sure this should run
  244. if (!history.replaceState || !options.updateURL || history.state) return;
  245. // Get the hash to use
  246. var hash = window.location.hash;
  247. hash = hash ? hash : '';
  248. // Set a default history
  249. history.replaceState(
  250. {
  251. smoothScroll: JSON.stringify(options),
  252. anchor: hash ? hash : window.pageYOffset
  253. },
  254. document.title,
  255. hash ? hash : window.location.href
  256. );
  257. };
  258. /**
  259. * Update the URL
  260. * @param {Node} anchor The anchor that was scrolled to
  261. * @param {Boolean} isNum If true, anchor is a number
  262. * @param {Object} options Settings for Smooth Scroll
  263. */
  264. var updateURL = function (anchor, isNum, options) {
  265. // Bail if the anchor is a number
  266. if (isNum) return;
  267. // Verify that pushState is supported and the updateURL option is enabled
  268. if (!history.pushState || !options.updateURL) return;
  269. // Update URL
  270. history.pushState(
  271. {
  272. smoothScroll: JSON.stringify(options),
  273. anchor: anchor.id
  274. },
  275. document.title,
  276. anchor === document.documentElement ? '#top' : '#' + anchor.id
  277. );
  278. };
  279. /**
  280. * Bring the anchored element into focus
  281. * @param {Node} anchor The anchor element
  282. * @param {Number} endLocation The end location to scroll to
  283. * @param {Boolean} isNum If true, scroll is to a position rather than an element
  284. */
  285. var adjustFocus = function (anchor, endLocation, isNum) {
  286. // Is scrolling to top of page, blur
  287. if (anchor === 0) {
  288. document.body.focus();
  289. }
  290. // Don't run if scrolling to a number on the page
  291. if (isNum) return;
  292. // Otherwise, bring anchor element into focus
  293. anchor.focus();
  294. if (document.activeElement !== anchor) {
  295. anchor.setAttribute('tabindex', '-1');
  296. anchor.focus();
  297. anchor.style.outline = 'none';
  298. }
  299. window.scrollTo(0 , endLocation);
  300. };
  301. /**
  302. * Emit a custom event
  303. * @param {String} type The event type
  304. * @param {Object} options The settings object
  305. * @param {Node} anchor The anchor element
  306. * @param {Node} toggle The toggle element
  307. */
  308. var emitEvent = function (type, options, anchor, toggle) {
  309. if (!options.emitEvents || typeof window.CustomEvent !== 'function') return;
  310. var event = new CustomEvent(type, {
  311. bubbles: true,
  312. detail: {
  313. anchor: anchor,
  314. toggle: toggle
  315. }
  316. });
  317. document.dispatchEvent(event);
  318. };
  319. //
  320. // SmoothScroll Constructor
  321. //
  322. var SmoothScroll = function (selector, options) {
  323. //
  324. // Variables
  325. //
  326. var smoothScroll = {}; // Object for public APIs
  327. var settings, anchor, toggle, fixedHeader, eventTimeout, animationInterval;
  328. //
  329. // Methods
  330. //
  331. /**
  332. * Cancel a scroll-in-progress
  333. */
  334. smoothScroll.cancelScroll = function (noEvent) {
  335. cancelAnimationFrame(animationInterval);
  336. animationInterval = null;
  337. if (noEvent) return;
  338. emitEvent('scrollCancel', settings);
  339. };
  340. /**
  341. * Start/stop the scrolling animation
  342. * @param {Node|Number} anchor The element or position to scroll to
  343. * @param {Element} toggle The element that toggled the scroll event
  344. * @param {Object} options
  345. */
  346. smoothScroll.animateScroll = function (anchor, toggle, options) {
  347. // Cancel any in progress scrolls
  348. smoothScroll.cancelScroll();
  349. // Local settings
  350. var _settings = extend(settings || defaults, options || {}); // Merge user options with defaults
  351. // Selectors and variables
  352. var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false;
  353. var anchorElem = isNum || !anchor.tagName ? null : anchor;
  354. if (!isNum && !anchorElem) return;
  355. var startLocation = window.pageYOffset; // Current location on the page
  356. if (_settings.header && !fixedHeader) {
  357. // Get the fixed header if not already set
  358. fixedHeader = document.querySelector(_settings.header);
  359. }
  360. var headerHeight = getHeaderHeight(fixedHeader);
  361. var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof _settings.offset === 'function' ? _settings.offset(anchor, toggle) : _settings.offset), 10), _settings.clip); // Location to scroll to
  362. var distance = endLocation - startLocation; // distance to travel
  363. var documentHeight = getDocumentHeight();
  364. var timeLapsed = 0;
  365. var speed = getSpeed(distance, _settings);
  366. var start, percentage, position;
  367. /**
  368. * Stop the scroll animation when it reaches its target (or the bottom/top of page)
  369. * @param {Number} position Current position on the page
  370. * @param {Number} endLocation Scroll to location
  371. * @param {Number} animationInterval How much to scroll on this loop
  372. */
  373. var stopAnimateScroll = function (position, endLocation) {
  374. // Get the current location
  375. var currentLocation = window.pageYOffset;
  376. // Check if the end location has been reached yet (or we've hit the end of the document)
  377. if (position == endLocation || currentLocation == endLocation || ((startLocation < endLocation && window.innerHeight + currentLocation) >= documentHeight)) {
  378. // Clear the animation timer
  379. smoothScroll.cancelScroll(true);
  380. // Bring the anchored element into focus
  381. adjustFocus(anchor, endLocation, isNum);
  382. // Emit a custom event
  383. emitEvent('scrollStop', _settings, anchor, toggle);
  384. // Reset start
  385. start = null;
  386. animationInterval = null;
  387. return true;
  388. }
  389. };
  390. /**
  391. * Loop scrolling animation
  392. */
  393. var loopAnimateScroll = function (timestamp) {
  394. if (!start) { start = timestamp; }
  395. timeLapsed += timestamp - start;
  396. percentage = speed === 0 ? 0 : (timeLapsed / speed);
  397. percentage = (percentage > 1) ? 1 : percentage;
  398. position = startLocation + (distance * easingPattern(_settings, percentage));
  399. window.scrollTo(0, Math.floor(position));
  400. if (!stopAnimateScroll(position, endLocation)) {
  401. animationInterval = window.requestAnimationFrame(loopAnimateScroll);
  402. start = timestamp;
  403. }
  404. };
  405. /**
  406. * Reset position to fix weird iOS bug
  407. * @link https://github.com/cferdinandi/smooth-scroll/issues/45
  408. */
  409. if (window.pageYOffset === 0) {
  410. window.scrollTo(0, 0);
  411. }
  412. // Update the URL
  413. updateURL(anchor, isNum, _settings);
  414. // If the user prefers reduced motion, jump to location
  415. if (reduceMotion()) {
  416. window.scrollTo(0, Math.floor(endLocation));
  417. return;
  418. }
  419. // Emit a custom event
  420. emitEvent('scrollStart', _settings, anchor, toggle);
  421. // Start scrolling animation
  422. smoothScroll.cancelScroll(true);
  423. window.requestAnimationFrame(loopAnimateScroll);
  424. };
  425. /**
  426. * If smooth scroll element clicked, animate scroll
  427. */
  428. var clickHandler = function (event) {
  429. // Don't run if event was canceled but still bubbled up
  430. // By @mgreter - https://github.com/cferdinandi/smooth-scroll/pull/462/
  431. if (event.defaultPrevented) return;
  432. // Don't run if right-click or command/control + click or shift + click
  433. if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return;
  434. // Check if event.target has closest() method
  435. // By @totegi - https://github.com/cferdinandi/smooth-scroll/pull/401/
  436. if (!('closest' in event.target)) return;
  437. // Check if a smooth scroll link was clicked
  438. toggle = event.target.closest(selector);
  439. if (!toggle || toggle.tagName.toLowerCase() !== 'a' || event.target.closest(settings.ignore)) return;
  440. // Only run if link is an anchor and points to the current page
  441. if (toggle.hostname !== window.location.hostname || toggle.pathname !== window.location.pathname || !/#/.test(toggle.href)) return;
  442. // Get an escaped version of the hash
  443. var hash = escapeCharacters(toggle.hash);
  444. // Get the anchored element
  445. var anchor;
  446. if (hash === '#') {
  447. if (!settings.topOnEmptyHash) return;
  448. anchor = document.documentElement;
  449. } else {
  450. anchor = document.querySelector(hash);
  451. }
  452. anchor = !anchor && hash === '#top' ? document.documentElement : anchor;
  453. // If anchored element exists, scroll to it
  454. if (!anchor) return;
  455. event.preventDefault();
  456. setHistory(settings);
  457. smoothScroll.animateScroll(anchor, toggle);
  458. };
  459. /**
  460. * Animate scroll on popstate events
  461. */
  462. var popstateHandler = function (event) {
  463. // Stop if history.state doesn't exist (ex. if clicking on a broken anchor link).
  464. // fixes `Cannot read property 'smoothScroll' of null` error getting thrown.
  465. if (history.state === null) return;
  466. // Only run if state is a popstate record for this instantiation
  467. if (!history.state.smoothScroll || history.state.smoothScroll !== JSON.stringify(settings)) return;
  468. // Only run if state includes an anchor
  469. // if (!history.state.anchor && history.state.anchor !== 0) return;
  470. // Get the anchor
  471. var anchor = history.state.anchor;
  472. if (typeof anchor === 'string' && anchor) {
  473. anchor = document.querySelector(escapeCharacters(history.state.anchor));
  474. if (!anchor) return;
  475. }
  476. // Animate scroll to anchor link
  477. smoothScroll.animateScroll(anchor, null, {updateURL: false});
  478. };
  479. /**
  480. * Destroy the current initialization.
  481. */
  482. smoothScroll.destroy = function () {
  483. // If plugin isn't already initialized, stop
  484. if (!settings) return;
  485. // Remove event listeners
  486. document.removeEventListener('click', clickHandler, false);
  487. window.removeEventListener('popstate', popstateHandler, false);
  488. // Cancel any scrolls-in-progress
  489. smoothScroll.cancelScroll();
  490. // Reset variables
  491. settings = null;
  492. anchor = null;
  493. toggle = null;
  494. fixedHeader = null;
  495. eventTimeout = null;
  496. animationInterval = null;
  497. };
  498. /**
  499. * Initialize Smooth Scroll
  500. * @param {Object} options User settings
  501. */
  502. var init = function () {
  503. // feature test
  504. if (!supports()) throw 'Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.';
  505. // Destroy any existing initializations
  506. smoothScroll.destroy();
  507. // Selectors and variables
  508. settings = extend(defaults, options || {}); // Merge user options with defaults
  509. fixedHeader = settings.header ? document.querySelector(settings.header) : null; // Get the fixed header
  510. // When a toggle is clicked, run the click handler
  511. document.addEventListener('click', clickHandler, false);
  512. // If updateURL and popState are enabled, listen for pop events
  513. if (settings.updateURL && settings.popstate) {
  514. window.addEventListener('popstate', popstateHandler, false);
  515. }
  516. };
  517. //
  518. // Initialize plugin
  519. //
  520. init();
  521. //
  522. // Public APIs
  523. //
  524. return smoothScroll;
  525. };
  526. return SmoothScroll;
  527. }));