PageRenderTime 20ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/smooth-scroll/5.0.4/js/smooth-scroll.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 350 lines | 181 code | 40 blank | 129 comment | 57 complexity | 411f24e70bea00f992b96f7392f7c642 MD5 | raw file
  1. /**
  2. * smooth-scroll v5.0.4
  3. * Animate scrolling to anchor links, by Chris Ferdinandi.
  4. * http://github.com/cferdinandi/smooth-scroll
  5. *
  6. * Free to use under the MIT License.
  7. * http://gomakethings.com/mit/
  8. */
  9. (function (root, factory) {
  10. if ( typeof define === 'function' && define.amd ) {
  11. define('smoothScroll', factory(root));
  12. } else if ( typeof exports === 'object' ) {
  13. module.exports = factory(root);
  14. } else {
  15. root.smoothScroll = factory(root);
  16. }
  17. })(this, function (root) {
  18. 'use strict';
  19. //
  20. // Variables
  21. //
  22. var smoothScroll = {}; // Object for public APIs
  23. var supports = !!document.querySelector && !!root.addEventListener; // Feature test
  24. var settings;
  25. // Default settings
  26. var defaults = {
  27. speed: 500,
  28. easing: 'easeInOutCubic',
  29. offset: 0,
  30. updateURL: true,
  31. callbackBefore: function () {},
  32. callbackAfter: function () {}
  33. };
  34. //
  35. // Methods
  36. //
  37. /**
  38. * A simple forEach() implementation for Arrays, Objects and NodeLists
  39. * @private
  40. * @param {Array|Object|NodeList} collection Collection of items to iterate
  41. * @param {Function} callback Callback function for each iteration
  42. * @param {Array|Object|NodeList} scope Object/NodeList/Array that forEach is iterating over (aka `this`)
  43. */
  44. var forEach = function (collection, callback, scope) {
  45. if (Object.prototype.toString.call(collection) === '[object Object]') {
  46. for (var prop in collection) {
  47. if (Object.prototype.hasOwnProperty.call(collection, prop)) {
  48. callback.call(scope, collection[prop], prop, collection);
  49. }
  50. }
  51. } else {
  52. for (var i = 0, len = collection.length; i < len; i++) {
  53. callback.call(scope, collection[i], i, collection);
  54. }
  55. }
  56. };
  57. /**
  58. * Merge defaults with user options
  59. * @private
  60. * @param {Object} defaults Default settings
  61. * @param {Object} options User options
  62. * @returns {Object} Merged values of defaults and options
  63. */
  64. var extend = function ( defaults, options ) {
  65. var extended = {};
  66. forEach(defaults, function (value, prop) {
  67. extended[prop] = defaults[prop];
  68. });
  69. forEach(options, function (value, prop) {
  70. extended[prop] = options[prop];
  71. });
  72. return extended;
  73. };
  74. /**
  75. * Escape special characters for use with querySelector
  76. * @private
  77. * @param {String} id The anchor ID to escape
  78. * @author Mathias Bynens
  79. * @link https://github.com/mathiasbynens/CSS.escape
  80. */
  81. var escapeCharacters = function ( id ) {
  82. var string = String(id);
  83. var length = string.length;
  84. var index = -1;
  85. var codeUnit;
  86. var result = '';
  87. var firstCodeUnit = string.charCodeAt(0);
  88. while (++index < length) {
  89. codeUnit = string.charCodeAt(index);
  90. // Note: there’s no need to special-case astral symbols, surrogate
  91. // pairs, or lone surrogates.
  92. // If the character is NULL (U+0000), then throw an
  93. // `InvalidCharacterError` exception and terminate these steps.
  94. if (codeUnit === 0x0000) {
  95. throw new InvalidCharacterError(
  96. 'Invalid character: the input contains U+0000.'
  97. );
  98. }
  99. if (
  100. // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
  101. // U+007F, […]
  102. (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F ||
  103. // If the character is the first character and is in the range [0-9]
  104. // (U+0030 to U+0039), […]
  105. (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
  106. // If the character is the second character and is in the range [0-9]
  107. // (U+0030 to U+0039) and the first character is a `-` (U+002D), […]
  108. (
  109. index === 1 &&
  110. codeUnit >= 0x0030 && codeUnit <= 0x0039 &&
  111. firstCodeUnit === 0x002D
  112. )
  113. ) {
  114. // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point
  115. result += '\\' + codeUnit.toString(16) + ' ';
  116. continue;
  117. }
  118. // If the character is not handled by one of the above rules and is
  119. // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or
  120. // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to
  121. // U+005A), or [a-z] (U+0061 to U+007A), […]
  122. if (
  123. codeUnit >= 0x0080 ||
  124. codeUnit === 0x002D ||
  125. codeUnit === 0x005F ||
  126. codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
  127. codeUnit >= 0x0041 && codeUnit <= 0x005A ||
  128. codeUnit >= 0x0061 && codeUnit <= 0x007A
  129. ) {
  130. // the character itself
  131. result += string.charAt(index);
  132. continue;
  133. }
  134. // Otherwise, the escaped character.
  135. // http://dev.w3.org/csswg/cssom/#escape-a-character
  136. result += '\\' + string.charAt(index);
  137. }
  138. return result;
  139. };
  140. /**
  141. * Calculate the easing pattern
  142. * @private
  143. * @param {String} type Easing pattern
  144. * @param {Number} time Time animation should take to complete
  145. * @returns {Number}
  146. */
  147. var easingPattern = function ( type, time ) {
  148. var pattern;
  149. if ( type === 'easeInQuad' ) pattern = time * time; // accelerating from zero velocity
  150. if ( type === 'easeOutQuad' ) pattern = time * (2 - time); // decelerating to zero velocity
  151. if ( type === 'easeInOutQuad' ) pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
  152. if ( type === 'easeInCubic' ) pattern = time * time * time; // accelerating from zero velocity
  153. if ( type === 'easeOutCubic' ) pattern = (--time) * time * time + 1; // decelerating to zero velocity
  154. if ( type === 'easeInOutCubic' ) pattern = time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
  155. if ( type === 'easeInQuart' ) pattern = time * time * time * time; // accelerating from zero velocity
  156. if ( type === 'easeOutQuart' ) pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity
  157. if ( type === 'easeInOutQuart' ) pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
  158. if ( type === 'easeInQuint' ) pattern = time * time * time * time * time; // accelerating from zero velocity
  159. if ( type === 'easeOutQuint' ) pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity
  160. if ( type === 'easeInOutQuint' ) pattern = time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
  161. return pattern || time; // no easing, no acceleration
  162. };
  163. /**
  164. * Calculate how far to scroll
  165. * @private
  166. * @param {Element} anchor The anchor element to scroll to
  167. * @param {Number} headerHeight Height of a fixed header, if any
  168. * @param {Number} offset Number of pixels by which to offset scroll
  169. * @returns {Number}
  170. */
  171. var getEndLocation = function ( anchor, headerHeight, offset ) {
  172. var location = 0;
  173. if (anchor.offsetParent) {
  174. do {
  175. location += anchor.offsetTop;
  176. anchor = anchor.offsetParent;
  177. } while (anchor);
  178. }
  179. location = location - headerHeight - offset;
  180. return location >= 0 ? location : 0;
  181. };
  182. /**
  183. * Determine the document's height
  184. * @private
  185. * @returns {Number}
  186. */
  187. var getDocumentHeight = function () {
  188. return Math.max(
  189. document.body.scrollHeight, document.documentElement.scrollHeight,
  190. document.body.offsetHeight, document.documentElement.offsetHeight,
  191. document.body.clientHeight, document.documentElement.clientHeight
  192. );
  193. };
  194. /**
  195. * Convert data-options attribute into an object of key/value pairs
  196. * @private
  197. * @param {String} options Link-specific options as a data attribute string
  198. * @returns {Object}
  199. */
  200. var getDataOptions = function ( options ) {
  201. return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse( options );
  202. };
  203. /**
  204. * Update the URL
  205. * @private
  206. * @param {Element} anchor The element to scroll to
  207. * @param {Boolean} url Whether or not to update the URL history
  208. */
  209. var updateUrl = function ( anchor, url ) {
  210. if ( history.pushState && (url || url === 'true') ) {
  211. history.pushState( {
  212. pos: anchor.id
  213. }, '', window.location.pathname + anchor );
  214. }
  215. };
  216. /**
  217. * Start/stop the scrolling animation
  218. * @public
  219. * @param {Element} toggle The element that toggled the scroll event
  220. * @param {Element} anchor The element to scroll to
  221. * @param {Object} settings
  222. * @param {Event} event
  223. */
  224. smoothScroll.animateScroll = function ( toggle, anchor, options, event ) {
  225. // Options and overrides
  226. var settings = extend( settings || defaults, options || {} ); // Merge user options with defaults
  227. var overrides = getDataOptions( toggle ? toggle.getAttribute('data-options') : null );
  228. settings = extend( settings, overrides );
  229. anchor = '#' + escapeCharacters(anchor.substr(1)); // Escape special characters and leading numbers
  230. // Selectors and variables
  231. var fixedHeader = document.querySelector('[data-scroll-header]'); // Get the fixed header
  232. var headerHeight = fixedHeader === null ? 0 : (fixedHeader.offsetHeight + fixedHeader.offsetTop); // Get the height of a fixed header if one exists
  233. var startLocation = root.pageYOffset; // Current location on the page
  234. var endLocation = getEndLocation( document.querySelector(anchor), headerHeight, parseInt(settings.offset, 10) ); // Scroll to location
  235. var animationInterval; // interval timer
  236. var distance = endLocation - startLocation; // distance to travel
  237. var documentHeight = getDocumentHeight();
  238. var timeLapsed = 0;
  239. var percentage, position;
  240. // Prevent default click event
  241. if ( toggle && toggle.tagName.toLowerCase() === 'a' && event ) {
  242. event.preventDefault();
  243. }
  244. // Update URL
  245. updateUrl(anchor, settings.updateURL);
  246. /**
  247. * Stop the scroll animation when it reaches its target (or the bottom/top of page)
  248. * @private
  249. * @param {Number} position Current position on the page
  250. * @param {Number} endLocation Scroll to location
  251. * @param {Number} animationInterval How much to scroll on this loop
  252. */
  253. var stopAnimateScroll = function (position, endLocation, animationInterval) {
  254. var currentLocation = root.pageYOffset;
  255. if ( position == endLocation || currentLocation == endLocation || ( (root.innerHeight + currentLocation) >= documentHeight ) ) {
  256. clearInterval(animationInterval);
  257. settings.callbackAfter( toggle, anchor ); // Run callbacks after animation complete
  258. }
  259. };
  260. /**
  261. * Loop scrolling animation
  262. * @private
  263. */
  264. var loopAnimateScroll = function () {
  265. timeLapsed += 16;
  266. percentage = ( timeLapsed / parseInt(settings.speed, 10) );
  267. percentage = ( percentage > 1 ) ? 1 : percentage;
  268. position = startLocation + ( distance * easingPattern(settings.easing, percentage) );
  269. root.scrollTo( 0, Math.floor(position) );
  270. stopAnimateScroll(position, endLocation, animationInterval);
  271. };
  272. /**
  273. * Set interval timer
  274. * @private
  275. */
  276. var startAnimateScroll = function () {
  277. settings.callbackBefore( toggle, anchor ); // Run callbacks before animating scroll
  278. animationInterval = setInterval(loopAnimateScroll, 16);
  279. };
  280. /**
  281. * Reset position to fix weird iOS bug
  282. * @link https://github.com/cferdinandi/smooth-scroll/issues/45
  283. */
  284. if ( root.pageYOffset === 0 ) {
  285. root.scrollTo( 0, 0 );
  286. }
  287. // Start scrolling animation
  288. startAnimateScroll();
  289. };
  290. /**
  291. * Initialize Smooth Scroll
  292. * @public
  293. * @param {Object} options User settings
  294. */
  295. smoothScroll.init = function ( options ) {
  296. // feature test
  297. if ( !supports ) return;
  298. // Selectors and variables
  299. settings = extend( defaults, options || {} ); // Merge user options with defaults
  300. var toggles = document.querySelectorAll('[data-scroll]'); // Get smooth scroll toggles
  301. // When a toggle is clicked, run the click handler
  302. forEach(toggles, function (toggle) {
  303. toggle.addEventListener('click', smoothScroll.animateScroll.bind( null, toggle, toggle.hash, settings ), false);
  304. });
  305. };
  306. //
  307. // Public APIs
  308. //
  309. return smoothScroll;
  310. });