PageRenderTime 61ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

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

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