Advertisement
Guest User

Untitled

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