PageRenderTime 29ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/Dev/AERRO/bower_components/smooth-scroll/dist/js/smooth-scroll.js

https://bitbucket.org/cbrs/national-convention
JavaScript | 484 lines | 423 code | 19 blank | 42 comment | 16 complexity | 89d8c7fa1368aef858ec60d1c23b6c34 MD5 | raw file
  1. /**
  2. * smooth-scroll v7.0.0
  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(['buoy'], factory(root));
  12. } else if ( typeof exports === 'object' ) {
  13. module.exports = factory(root, require('buoy'));
  14. } else {
  15. root.smoothScroll = factory(root, root.buoy);
  16. }
  17. })(typeof global !== 'undefined' ? global : this.window || this.global, function (root) {
  18. 'use strict';
  19. //
  20. // Variables
  21. //
  22. var smoothScroll = {}; // Object for public APIs
  23. var supports = !!root.document.querySelector && !!root.addEventListener; // Feature test
  24. var settings, eventTimeout, fixedHeader, headerHeight;
  25. // Default settings
  26. var defaults = {
  27. speed: 500,
  28. easing: 'easeInOutCubic',
  29. offset: 0,
  30. updateURL: true,
  31. callback: function () {}
  32. };
  33. //
  34. // Methods
  35. //
  36. /**
  37. * Merge two or more objects. Returns a new object.
  38. * @private
  39. * @param {Boolean} deep If true, do a deep (or recursive) merge [optional]
  40. * @param {Object} objects The objects to merge together
  41. * @returns {Object} Merged values of defaults and options
  42. */
  43. var extend = function () {
  44. // Variables
  45. var extended = {};
  46. var deep = false;
  47. var i = 0;
  48. var length = arguments.length;
  49. // Check if a deep merge
  50. if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) {
  51. deep = arguments[0];
  52. i++;
  53. }
  54. // Merge the object into the extended object
  55. var merge = function (obj) {
  56. for ( var prop in obj ) {
  57. if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
  58. // If deep merge and property is an object, merge properties
  59. if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) {
  60. extended[prop] = extend( true, extended[prop], obj[prop] );
  61. } else {
  62. extended[prop] = obj[prop];
  63. }
  64. }
  65. }
  66. };
  67. // Loop through each object and conduct a merge
  68. for ( ; i < length; i++ ) {
  69. var obj = arguments[i];
  70. merge(obj);
  71. }
  72. return extended;
  73. };
  74. /**
  75. * Get the height of an element.
  76. * @private
  77. * @param {Node} elem The element to get the height of
  78. * @return {Number} The element's height in pixels
  79. */
  80. var getHeight = function ( elem ) {
  81. return Math.max( elem.scrollHeight, elem.offsetHeight, elem.clientHeight );
  82. };
  83. /**
  84. * Get the closest matching element up the DOM tree.
  85. * @private
  86. * @param {Element} elem Starting element
  87. * @param {String} selector Selector to match against (class, ID, data attribute, or tag)
  88. * @return {Boolean|Element} Returns null if not match found
  89. */
  90. var getClosest = function ( elem, selector ) {
  91. // Variables
  92. var firstChar = selector.charAt(0);
  93. var supports = 'classList' in document.documentElement;
  94. var attribute, value;
  95. // If selector is a data attribute, split attribute from value
  96. if ( firstChar === '[' ) {
  97. selector = selector.substr(1, selector.length - 2);
  98. attribute = selector.split( '=' );
  99. if ( attribute.length > 1 ) {
  100. value = true;
  101. attribute[1] = attribute[1].replace( /"/g, '' ).replace( /'/g, '' );
  102. }
  103. }
  104. // Get closest match
  105. for ( ; elem && elem !== document; elem = elem.parentNode ) {
  106. // If selector is a class
  107. if ( firstChar === '.' ) {
  108. if ( supports ) {
  109. if ( elem.classList.contains( selector.substr(1) ) ) {
  110. return elem;
  111. }
  112. } else {
  113. if ( new RegExp('(^|\\s)' + selector.substr(1) + '(\\s|$)').test( elem.className ) ) {
  114. return elem;
  115. }
  116. }
  117. }
  118. // If selector is an ID
  119. if ( firstChar === '#' ) {
  120. if ( elem.id === selector.substr(1) ) {
  121. return elem;
  122. }
  123. }
  124. // If selector is a data attribute
  125. if ( firstChar === '[' ) {
  126. if ( elem.hasAttribute( attribute[0] ) ) {
  127. if ( value ) {
  128. if ( elem.getAttribute( attribute[0] ) === attribute[1] ) {
  129. return elem;
  130. }
  131. } else {
  132. return elem;
  133. }
  134. }
  135. }
  136. // If selector is a tag
  137. if ( elem.tagName.toLowerCase() === selector ) {
  138. return elem;
  139. }
  140. }
  141. return null;
  142. };
  143. /**
  144. * Escape special characters for use with querySelector
  145. * @private
  146. * @param {String} id The anchor ID to escape
  147. * @author Mathias Bynens
  148. * @link https://github.com/mathiasbynens/CSS.escape
  149. */
  150. var escapeCharacters = function ( id ) {
  151. var string = String(id);
  152. var length = string.length;
  153. var index = -1;
  154. var codeUnit;
  155. var result = '';
  156. var firstCodeUnit = string.charCodeAt(0);
  157. while (++index < length) {
  158. codeUnit = string.charCodeAt(index);
  159. // Note: there’s no need to special-case astral symbols, surrogate
  160. // pairs, or lone surrogates.
  161. // If the character is NULL (U+0000), then throw an
  162. // `InvalidCharacterError` exception and terminate these steps.
  163. if (codeUnit === 0x0000) {
  164. throw new InvalidCharacterError(
  165. 'Invalid character: the input contains U+0000.'
  166. );
  167. }
  168. if (
  169. // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
  170. // U+007F, […]
  171. (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F ||
  172. // If the character is the first character and is in the range [0-9]
  173. // (U+0030 to U+0039), […]
  174. (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) ||
  175. // If the character is the second character and is in the range [0-9]
  176. // (U+0030 to U+0039) and the first character is a `-` (U+002D), […]
  177. (
  178. index === 1 &&
  179. codeUnit >= 0x0030 && codeUnit <= 0x0039 &&
  180. firstCodeUnit === 0x002D
  181. )
  182. ) {
  183. // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point
  184. result += '\\' + codeUnit.toString(16) + ' ';
  185. continue;
  186. }
  187. // If the character is not handled by one of the above rules and is
  188. // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or
  189. // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to
  190. // U+005A), or [a-z] (U+0061 to U+007A), […]
  191. if (
  192. codeUnit >= 0x0080 ||
  193. codeUnit === 0x002D ||
  194. codeUnit === 0x005F ||
  195. codeUnit >= 0x0030 && codeUnit <= 0x0039 ||
  196. codeUnit >= 0x0041 && codeUnit <= 0x005A ||
  197. codeUnit >= 0x0061 && codeUnit <= 0x007A
  198. ) {
  199. // the character itself
  200. result += string.charAt(index);
  201. continue;
  202. }
  203. // Otherwise, the escaped character.
  204. // http://dev.w3.org/csswg/cssom/#escape-a-character
  205. result += '\\' + string.charAt(index);
  206. }
  207. return result;
  208. };
  209. /**
  210. * Calculate the easing pattern
  211. * @private
  212. * @link https://gist.github.com/gre/1650294
  213. * @param {String} type Easing pattern
  214. * @param {Number} time Time animation should take to complete
  215. * @returns {Number}
  216. */
  217. var easingPattern = function ( type, time ) {
  218. var pattern;
  219. if ( type === 'easeInQuad' ) pattern = time * time; // accelerating from zero velocity
  220. if ( type === 'easeOutQuad' ) pattern = time * (2 - time); // decelerating to zero velocity
  221. if ( type === 'easeInOutQuad' ) pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
  222. if ( type === 'easeInCubic' ) pattern = time * time * time; // accelerating from zero velocity
  223. if ( type === 'easeOutCubic' ) pattern = (--time) * time * time + 1; // decelerating to zero velocity
  224. 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
  225. if ( type === 'easeInQuart' ) pattern = time * time * time * time; // accelerating from zero velocity
  226. if ( type === 'easeOutQuart' ) pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity
  227. if ( type === 'easeInOutQuart' ) pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
  228. if ( type === 'easeInQuint' ) pattern = time * time * time * time * time; // accelerating from zero velocity
  229. if ( type === 'easeOutQuint' ) pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity
  230. 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
  231. return pattern || time; // no easing, no acceleration
  232. };
  233. /**
  234. * Calculate how far to scroll
  235. * @private
  236. * @param {Element} anchor The anchor element to scroll to
  237. * @param {Number} headerHeight Height of a fixed header, if any
  238. * @param {Number} offset Number of pixels by which to offset scroll
  239. * @returns {Number}
  240. */
  241. var getEndLocation = function ( anchor, headerHeight, offset ) {
  242. var location = 0;
  243. if (anchor.offsetParent) {
  244. do {
  245. location += anchor.offsetTop;
  246. anchor = anchor.offsetParent;
  247. } while (anchor);
  248. }
  249. location = location - headerHeight - offset;
  250. return location >= 0 ? location : 0;
  251. };
  252. /**
  253. * Determine the document's height
  254. * @private
  255. * @returns {Number}
  256. */
  257. var getDocumentHeight = function () {
  258. return Math.max(
  259. root.document.body.scrollHeight, root.document.documentElement.scrollHeight,
  260. root.document.body.offsetHeight, root.document.documentElement.offsetHeight,
  261. root.document.body.clientHeight, root.document.documentElement.clientHeight
  262. );
  263. };
  264. /**
  265. * Convert data-options attribute into an object of key/value pairs
  266. * @private
  267. * @param {String} options Link-specific options as a data attribute string
  268. * @returns {Object}
  269. */
  270. var getDataOptions = function ( options ) {
  271. return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse( options );
  272. };
  273. /**
  274. * Update the URL
  275. * @private
  276. * @param {Element} anchor The element to scroll to
  277. * @param {Boolean} url Whether or not to update the URL history
  278. */
  279. var updateUrl = function ( anchor, url ) {
  280. if ( root.history.pushState && (url || url === 'true') ) {
  281. root.history.pushState( null, null, [root.location.protocol, '//', root.location.host, root.location.pathname, root.location.search, anchor].join('') );
  282. }
  283. };
  284. var getHeaderHeight = function ( header ) {
  285. return header === null ? 0 : ( getHeight( header ) + header.offsetTop );
  286. };
  287. /**
  288. * Start/stop the scrolling animation
  289. * @public
  290. * @param {Element} toggle The element that toggled the scroll event
  291. * @param {Element} anchor The element to scroll to
  292. * @param {Object} options
  293. */
  294. smoothScroll.animateScroll = function ( toggle, anchor, options ) {
  295. // Options and overrides
  296. var overrides = getDataOptions( toggle ? toggle.getAttribute('data-options') : null );
  297. var settings = extend( settings || defaults, options || {}, overrides ); // Merge user options with defaults
  298. anchor = '#' + escapeCharacters(anchor.substr(1)); // Escape special characters and leading numbers
  299. // Selectors and variables
  300. var anchorElem = anchor === '#' ? root.document.documentElement : root.document.querySelector(anchor);
  301. var startLocation = root.pageYOffset; // Current location on the page
  302. if ( !fixedHeader ) { fixedHeader = root.document.querySelector('[data-scroll-header]'); } // Get the fixed header if not already set
  303. if ( !headerHeight ) { headerHeight = getHeaderHeight( fixedHeader ); } // Get the height of a fixed header if one exists and not already set
  304. var endLocation = getEndLocation( anchorElem, headerHeight, parseInt(settings.offset, 10) ); // Scroll to location
  305. var animationInterval; // interval timer
  306. var distance = endLocation - startLocation; // distance to travel
  307. var documentHeight = getDocumentHeight();
  308. var timeLapsed = 0;
  309. var percentage, position;
  310. // Update URL
  311. updateUrl(anchor, settings.updateURL);
  312. /**
  313. * Stop the scroll animation when it reaches its target (or the bottom/top of page)
  314. * @private
  315. * @param {Number} position Current position on the page
  316. * @param {Number} endLocation Scroll to location
  317. * @param {Number} animationInterval How much to scroll on this loop
  318. */
  319. var stopAnimateScroll = function (position, endLocation, animationInterval) {
  320. var currentLocation = root.pageYOffset;
  321. if ( position == endLocation || currentLocation == endLocation || ( (root.innerHeight + currentLocation) >= documentHeight ) ) {
  322. clearInterval(animationInterval);
  323. anchorElem.focus();
  324. settings.callback( toggle, anchor ); // Run callbacks after animation complete
  325. }
  326. };
  327. /**
  328. * Loop scrolling animation
  329. * @private
  330. */
  331. var loopAnimateScroll = function () {
  332. timeLapsed += 16;
  333. percentage = ( timeLapsed / parseInt(settings.speed, 10) );
  334. percentage = ( percentage > 1 ) ? 1 : percentage;
  335. position = startLocation + ( distance * easingPattern(settings.easing, percentage) );
  336. root.scrollTo( 0, Math.floor(position) );
  337. stopAnimateScroll(position, endLocation, animationInterval);
  338. };
  339. /**
  340. * Set interval timer
  341. * @private
  342. */
  343. var startAnimateScroll = function () {
  344. animationInterval = setInterval(loopAnimateScroll, 16);
  345. };
  346. /**
  347. * Reset position to fix weird iOS bug
  348. * @link https://github.com/cferdinandi/smooth-scroll/issues/45
  349. */
  350. if ( root.pageYOffset === 0 ) {
  351. root.scrollTo( 0, 0 );
  352. }
  353. // Start scrolling animation
  354. startAnimateScroll();
  355. };
  356. /**
  357. * If smooth scroll element clicked, animate scroll
  358. * @private
  359. */
  360. var eventHandler = function (event) {
  361. var toggle = getClosest(event.target, '[data-scroll]');
  362. if ( toggle && toggle.tagName.toLowerCase() === 'a' ) {
  363. event.preventDefault(); // Prevent default click event
  364. smoothScroll.animateScroll( toggle, toggle.hash, settings); // Animate scroll
  365. }
  366. };
  367. /**
  368. * On window scroll and resize, only run events at a rate of 15fps for better performance
  369. * @private
  370. * @param {Function} eventTimeout Timeout function
  371. * @param {Object} settings
  372. */
  373. var eventThrottler = function (event) {
  374. if ( !eventTimeout ) {
  375. eventTimeout = setTimeout(function() {
  376. eventTimeout = null; // Reset timeout
  377. headerHeight = getHeaderHeight( fixedHeader ); // Get the height of a fixed header if one exists
  378. }, 66);
  379. }
  380. };
  381. /**
  382. * Destroy the current initialization.
  383. * @public
  384. */
  385. smoothScroll.destroy = function () {
  386. // If plugin isn't already initialized, stop
  387. if ( !settings ) return;
  388. // Remove event listeners
  389. root.document.removeEventListener( 'click', eventHandler, false );
  390. root.removeEventListener( 'resize', eventThrottler, false );
  391. // Reset varaibles
  392. settings = null;
  393. eventTimeout = null;
  394. fixedHeader = null;
  395. headerHeight = null;
  396. };
  397. /**
  398. * Initialize Smooth Scroll
  399. * @public
  400. * @param {Object} options User settings
  401. */
  402. smoothScroll.init = function ( options ) {
  403. // feature test
  404. if ( !supports ) return;
  405. // Destroy any existing initializations
  406. smoothScroll.destroy();
  407. // Selectors and variables
  408. settings = extend( defaults, options || {} ); // Merge user options with defaults
  409. fixedHeader = root.document.querySelector('[data-scroll-header]'); // Get the fixed header
  410. headerHeight = getHeaderHeight( fixedHeader );
  411. // When a toggle is clicked, run the click handler
  412. root.document.addEventListener('click', eventHandler, false );
  413. if ( fixedHeader ) { root.addEventListener( 'resize', eventThrottler, false ); }
  414. };
  415. //
  416. // Public APIs
  417. //
  418. return smoothScroll;
  419. });