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.

smooth-scroll.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*!
  2. * smooth-scroll v12.1.5: Animate scrolling to anchor links
  3. * (c) 2017 Chris Ferdinandi
  4. * MIT License
  5. * http://github.com/cferdinandi/smooth-scroll
  6. */
  7. (function (root, factory) {
  8. if ( typeof define === 'function' && define.amd ) {
  9. define([], (function () {
  10. return factory(root);
  11. }));
  12. } else if ( typeof exports === 'object' ) {
  13. module.exports = factory(root);
  14. } else {
  15. root.SmoothScroll = factory(root);
  16. }
  17. })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
  18. 'use strict';
  19. //
  20. // Feature Test
  21. //
  22. var supports =
  23. 'querySelector' in document &&
  24. 'addEventListener' in window &&
  25. 'requestAnimationFrame' in window &&
  26. 'closest' in window.Element.prototype;
  27. //
  28. // Default settings
  29. //
  30. var defaults = {
  31. // Selectors
  32. ignore: '[data-scroll-ignore]',
  33. header: null,
  34. // Speed & Easing
  35. speed: 500,
  36. offset: 0,
  37. easing: 'easeInOutCubic',
  38. customEasing: null,
  39. // Callback API
  40. before: function () {},
  41. after: function () {}
  42. };
  43. //
  44. // Utility Methods
  45. //
  46. /**
  47. * Merge two or more objects. Returns a new object.
  48. * @param {Object} objects The objects to merge together
  49. * @returns {Object} Merged values of defaults and options
  50. */
  51. var extend = function () {
  52. // Variables
  53. var extended = {};
  54. var deep = false;
  55. var i = 0;
  56. var length = arguments.length;
  57. // Merge the object into the extended object
  58. var merge = function (obj) {
  59. for (var prop in obj) {
  60. if (obj.hasOwnProperty(prop)) {
  61. extended[prop] = obj[prop];
  62. }
  63. }
  64. };
  65. // Loop through each object and conduct a merge
  66. for ( ; i < length; i++ ) {
  67. var obj = arguments[i];
  68. merge(obj);
  69. }
  70. return extended;
  71. };
  72. /**
  73. * Get the height of an element.
  74. * @param {Node} elem The element to get the height of
  75. * @return {Number} The element's height in pixels
  76. */
  77. var getHeight = function (elem) {
  78. return parseInt(window.getComputedStyle(elem).height, 10);
  79. };
  80. /**
  81. * Escape special characters for use with querySelector
  82. * @param {String} id The anchor ID to escape
  83. * @author Mathias Bynens
  84. * @link https://github.com/mathiasbynens/CSS.escape
  85. */
  86. var escapeCharacters = function (id) {
  87. // Remove leading hash
  88. if (id.charAt(0) === '#') {
  89. id = id.substr(1);
  90. }
  91. var string = String(id);
  92. var length = string.length;
  93. var index = -1;
  94. var codeUnit;
  95. var result = '';
  96. var firstCodeUnit = string.charCodeAt(0);
  97. while (++index < length) {
  98. codeUnit = string.charCodeAt(index);
  99. // Note: there’s no need to special-case astral symbols, surrogate
  100. // pairs, or lone surrogates.
  101. // If the character is NULL (U+0000), then throw an
  102. // `InvalidCharacterError` exception and terminate these steps.
  103. if (codeUnit === 0x0000) {
  104. throw new InvalidCharacterError(
  105. 'Invalid character: the input contains U+0000.'
  106. );
  107. }
  108. if (
  109. // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
  110. // U+007F, […]
  111. (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F ||
  112. // If the character is the first character and is in the range [0-9]
  113. // (U+0030 to U+0039), […]
  114. (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
  115. // If the character is the second character and is in the range [0-9]
  116. // (U+0030 to U+0039) and the first character is a `-` (U+002D), […]
  117. (
  118. index === 1 &&
  119. codeUnit >= 0x0030 && codeUnit <= 0x0039 &&
  120. firstCodeUnit === 0x002D
  121. )
  122. ) {
  123. // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point
  124. result += '\\' + codeUnit.toString(16) + ' ';
  125. continue;
  126. }
  127. // If the character is not handled by one of the above rules and is
  128. // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or
  129. // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to
  130. // U+005A), or [a-z] (U+0061 to U+007A), […]
  131. if (
  132. codeUnit >= 0x0080 ||
  133. codeUnit === 0x002D ||
  134. codeUnit === 0x005F ||
  135. codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
  136. codeUnit >= 0x0041 && codeUnit <= 0x005A ||
  137. codeUnit >= 0x0061 && codeUnit <= 0x007A
  138. ) {
  139. // the character itself
  140. result += string.charAt(index);
  141. continue;
  142. }
  143. // Otherwise, the escaped character.
  144. // http://dev.w3.org/csswg/cssom/#escape-a-character
  145. result += '\\' + string.charAt(index);
  146. }
  147. return '#' + result;
  148. };
  149. /**
  150. * Calculate the easing pattern
  151. * @link https://gist.github.com/gre/1650294
  152. * @param {String} type Easing pattern
  153. * @param {Number} time Time animation should take to complete
  154. * @returns {Number}
  155. */
  156. var easingPattern = function (settings, time) {
  157. var pattern;
  158. // Default Easing Patterns
  159. if (settings.easing === 'easeInQuad') pattern = time * time; // accelerating from zero velocity
  160. if (settings.easing === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity
  161. if (settings.easing === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
  162. if (settings.easing === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity
  163. if (settings.easing === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity
  164. 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
  165. if (settings.easing === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity
  166. if (settings.easing === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity
  167. if (settings.easing === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
  168. if (settings.easing === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity
  169. if (settings.easing === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity
  170. 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
  171. // Custom Easing Patterns
  172. if (!!settings.customEasing) pattern = settings.customEasing(time);
  173. return pattern || time; // no easing, no acceleration
  174. };
  175. /**
  176. * Determine the document's height
  177. * @returns {Number}
  178. */
  179. var getDocumentHeight = function () {
  180. return Math.max(
  181. document.body.scrollHeight, document.documentElement.scrollHeight,
  182. document.body.offsetHeight, document.documentElement.offsetHeight,
  183. document.body.clientHeight, document.documentElement.clientHeight
  184. );
  185. };
  186. /**
  187. * Calculate how far to scroll
  188. * @param {Element} anchor The anchor element to scroll to
  189. * @param {Number} headerHeight Height of a fixed header, if any
  190. * @param {Number} offset Number of pixels by which to offset scroll
  191. * @returns {Number}
  192. */
  193. var getEndLocation = function (anchor, headerHeight, offset) {
  194. var location = 0;
  195. if (anchor.offsetParent) {
  196. do {
  197. location += anchor.offsetTop;
  198. anchor = anchor.offsetParent;
  199. } while (anchor);
  200. }
  201. location = Math.max(location - headerHeight - offset, 0);
  202. return location;
  203. };
  204. /**
  205. * Get the height of the fixed header
  206. * @param {Node} header The header
  207. * @return {Number} The height of the header
  208. */
  209. var getHeaderHeight = function (header) {
  210. return !header ? 0 : (getHeight(header) + header.offsetTop);
  211. };
  212. /**
  213. * Bring the anchored element into focus
  214. * @param {Node} anchor The anchor element
  215. * @param {Number} endLocation The end location to scroll to
  216. * @param {Boolean} isNum If true, scroll is to a position rather than an element
  217. */
  218. var adjustFocus = function (anchor, endLocation, isNum) {
  219. // Don't run if scrolling to a number on the page
  220. if (isNum) return;
  221. // Otherwise, bring anchor element into focus
  222. anchor.focus();
  223. if (document.activeElement.id !== anchor.id) {
  224. anchor.setAttribute('tabindex', '-1');
  225. anchor.focus();
  226. anchor.style.outline = 'none';
  227. }
  228. window.scrollTo(0 , endLocation);
  229. };
  230. /**
  231. * Check to see if user prefers reduced motion
  232. * @param {Object} settings Script settings
  233. */
  234. var reduceMotion = function (settings) {
  235. if ('matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches) {
  236. return true;
  237. }
  238. return false;
  239. };
  240. //
  241. // SmoothScroll Constructor
  242. //
  243. var SmoothScroll = function (selector, options) {
  244. //
  245. // Variables
  246. //
  247. var smoothScroll = {}; // Object for public APIs
  248. var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval;
  249. //
  250. // Methods
  251. //
  252. /**
  253. * Cancel a scroll-in-progress
  254. */
  255. smoothScroll.cancelScroll = function () {
  256. // clearInterval(animationInterval);
  257. cancelAnimationFrame(animationInterval);
  258. };
  259. /**
  260. * Start/stop the scrolling animation
  261. * @param {Node|Number} anchor The element or position to scroll to
  262. * @param {Element} toggle The element that toggled the scroll event
  263. * @param {Object} options
  264. */
  265. smoothScroll.animateScroll = function (anchor, toggle, options) {
  266. // Local settings
  267. var animateSettings = extend(settings || defaults, options || {}); // Merge user options with defaults
  268. // Selectors and variables
  269. var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false;
  270. var anchorElem = isNum || !anchor.tagName ? null : anchor;
  271. if (!isNum && !anchorElem) return;
  272. var startLocation = window.pageYOffset; // Current location on the page
  273. if (animateSettings.header && !fixedHeader) {
  274. // Get the fixed header if not already set
  275. fixedHeader = document.querySelector( animateSettings.header );
  276. }
  277. if (!headerHeight) {
  278. // Get the height of a fixed header if one exists and not already set
  279. headerHeight = getHeaderHeight(fixedHeader);
  280. }
  281. var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to
  282. var distance = endLocation - startLocation; // distance to travel
  283. var documentHeight = getDocumentHeight();
  284. var timeLapsed = 0;
  285. var start, percentage, position;
  286. /**
  287. * Stop the scroll animation when it reaches its target (or the bottom/top of page)
  288. * @param {Number} position Current position on the page
  289. * @param {Number} endLocation Scroll to location
  290. * @param {Number} animationInterval How much to scroll on this loop
  291. */
  292. var stopAnimateScroll = function (position, endLocation) {
  293. // Get the current location
  294. var currentLocation = window.pageYOffset;
  295. // Check if the end location has been reached yet (or we've hit the end of the document)
  296. if ( position == endLocation || currentLocation == endLocation || ((startLocation < endLocation && window.innerHeight + currentLocation) >= documentHeight )) {
  297. // Clear the animation timer
  298. smoothScroll.cancelScroll();
  299. // Bring the anchored element into focus
  300. adjustFocus(anchor, endLocation, isNum);
  301. // Run callback after animation complete
  302. animateSettings.after(anchor, toggle);
  303. // Reset start
  304. start = null;
  305. return true;
  306. }
  307. };
  308. /**
  309. * Loop scrolling animation
  310. */
  311. var loopAnimateScroll = function (timestamp) {
  312. if (!start) { start = timestamp; }
  313. timeLapsed += timestamp - start;
  314. percentage = (timeLapsed / parseInt(animateSettings.speed, 10));
  315. percentage = (percentage > 1) ? 1 : percentage;
  316. position = startLocation + (distance * easingPattern(animateSettings, percentage));
  317. window.scrollTo(0, Math.floor(position));
  318. if (!stopAnimateScroll(position, endLocation)) {
  319. window.requestAnimationFrame(loopAnimateScroll);
  320. start = timestamp;
  321. }
  322. };
  323. /**
  324. * Reset position to fix weird iOS bug
  325. * @link https://github.com/cferdinandi/smooth-scroll/issues/45
  326. */
  327. if (window.pageYOffset === 0) {
  328. window.scrollTo( 0, 0 );
  329. }
  330. // Run callback before animation starts
  331. animateSettings.before(anchor, toggle);
  332. // Start scrolling animation
  333. smoothScroll.cancelScroll();
  334. window.requestAnimationFrame(loopAnimateScroll);
  335. };
  336. /**
  337. * Handle has change event
  338. */
  339. var hashChangeHandler = function (event) {
  340. // Only run if there's an anchor element to scroll to
  341. if (!anchor) return;
  342. // Reset the anchor element's ID
  343. anchor.id = anchor.getAttribute('data-scroll-id');
  344. // Scroll to the anchored content
  345. smoothScroll.animateScroll(anchor, toggle);
  346. // Reset anchor and toggle
  347. anchor = null;
  348. toggle = null;
  349. };
  350. /**
  351. * If smooth scroll element clicked, animate scroll
  352. */
  353. var clickHandler = function (event) {
  354. // Don't run if the user prefers reduced motion
  355. if (reduceMotion(settings)) return;
  356. // Don't run if right-click or command/control + click
  357. if (event.button !== 0 || event.metaKey || event.ctrlKey) return;
  358. // Check if a smooth scroll link was clicked
  359. toggle = event.target.closest(selector);
  360. if (!toggle || toggle.tagName.toLowerCase() !== 'a' || event.target.closest(settings.ignore)) return;
  361. // Only run if link is an anchor and points to the current page
  362. if (toggle.hostname !== window.location.hostname || toggle.pathname !== window.location.pathname || !/#/.test(toggle.href)) return;
  363. // Get the sanitized hash
  364. var hash;
  365. try {
  366. hash = escapeCharacters(decodeURIComponent(toggle.hash));
  367. } catch(e) {
  368. hash = escapeCharacters(toggle.hash);
  369. }
  370. // If the hash is empty, scroll to the top of the page
  371. if (hash === '#') {
  372. // Prevent default link behavior
  373. event.preventDefault();
  374. // Set the anchored element
  375. anchor = document.body;
  376. // Save or create the ID as a data attribute and remove it (prevents scroll jump)
  377. var id = anchor.id ? anchor.id : 'smooth-scroll-top';
  378. anchor.setAttribute('data-scroll-id', id);
  379. anchor.id = '';
  380. // If no hash change event will happen, fire manually
  381. // Otherwise, update the hash
  382. if (window.location.hash.substring(1) === id) {
  383. hashChangeHandler();
  384. } else {
  385. window.location.hash = id;
  386. }
  387. return;
  388. }
  389. // Get the anchored element
  390. anchor = document.querySelector(hash);
  391. // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump)
  392. if (!anchor) return;
  393. anchor.setAttribute('data-scroll-id', anchor.id);
  394. anchor.id = '';
  395. // If no hash change event will happen, fire manually
  396. if (toggle.hash === window.location.hash) {
  397. event.preventDefault();
  398. hashChangeHandler();
  399. }
  400. };
  401. /**
  402. * On window scroll and resize, only run events at a rate of 15fps for better performance
  403. */
  404. var resizeThrottler = function (event) {
  405. if (!eventTimeout) {
  406. eventTimeout = setTimeout((function() {
  407. eventTimeout = null; // Reset timeout
  408. headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists
  409. }), 66);
  410. }
  411. };
  412. /**
  413. * Destroy the current initialization.
  414. */
  415. smoothScroll.destroy = function () {
  416. // If plugin isn't already initialized, stop
  417. if (!settings) return;
  418. // Remove event listeners
  419. document.removeEventListener('click', clickHandler, false);
  420. window.removeEventListener('resize', resizeThrottler, false);
  421. // Cancel any scrolls-in-progress
  422. smoothScroll.cancelScroll();
  423. // Reset variables
  424. settings = null;
  425. anchor = null;
  426. toggle = null;
  427. fixedHeader = null;
  428. headerHeight = null;
  429. eventTimeout = null;
  430. animationInterval = null;
  431. };
  432. /**
  433. * Initialize Smooth Scroll
  434. * @param {Object} options User settings
  435. */
  436. smoothScroll.init = function (options) {
  437. // feature test
  438. if (!supports) return;
  439. // Destroy any existing initializations
  440. smoothScroll.destroy();
  441. // Selectors and variables
  442. settings = extend(defaults, options || {}); // Merge user options with defaults
  443. fixedHeader = settings.header ? document.querySelector(settings.header) : null; // Get the fixed header
  444. headerHeight = getHeaderHeight(fixedHeader);
  445. // When a toggle is clicked, run the click handler
  446. document.addEventListener('click', clickHandler, false);
  447. // Listen for hash changes
  448. window.addEventListener('hashchange', hashChangeHandler, false);
  449. // If window is resized and there's a fixed header, recalculate its size
  450. if (fixedHeader) {
  451. window.addEventListener('resize', resizeThrottler, false);
  452. }
  453. };
  454. //
  455. // Initialize plugin
  456. //
  457. smoothScroll.init(options);
  458. //
  459. // Public APIs
  460. //
  461. return smoothScroll;
  462. };
  463. return SmoothScroll;
  464. }));