From ae2562b5a911cf7474da035a4195a46fa210e2ca Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Sat, 29 Apr 2017 02:41:07 +0200 Subject: [PATCH 1/7] Replace wrapper with export. Remove closest polyfill. --- src/js/smooth-scroll.js | 955 +++++++++++++++++++--------------------- 1 file changed, 451 insertions(+), 504 deletions(-) diff --git a/src/js/smooth-scroll.js b/src/js/smooth-scroll.js index 2dae938..ffd8dd3 100755 --- a/src/js/smooth-scroll.js +++ b/src/js/smooth-scroll.js @@ -1,576 +1,523 @@ -(function (root, factory) { - if ( typeof define === 'function' && define.amd ) { - define([], factory(root)); - } else if ( typeof exports === 'object' ) { - module.exports = factory(root); - } else { - root.smoothScroll = factory(root); - } -})(typeof global !== 'undefined' ? global : this.window || this.global, function (root) { - - 'use strict'; +var smoothScroll = {}; // Object for public APIs +var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test +var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; + +// Default settings +var defaults = { + selector: '[data-scroll]', + selectorHeader: null, + speed: 500, + easing: 'easeInOutCubic', + offset: 0, + callback: function () { } +}; + +// +// Methods +// + +/** + * Merge two or more objects. Returns a new object. + * @private + * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] + * @param {Object} objects The objects to merge together + * @returns {Object} Merged values of defaults and options + */ +var extend = function () { - // // Variables - // - - var smoothScroll = {}; // Object for public APIs - var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test - var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - - // Default settings - var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () {} - }; - - - // - // Methods - // - - /** - * Merge two or more objects. Returns a new object. - * @private - * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] - * @param {Object} objects The objects to merge together - * @returns {Object} Merged values of defaults and options - */ - var extend = function () { - - // Variables - var extended = {}; - var deep = false; - var i = 0; - var length = arguments.length; - - // Check if a deep merge - if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) { - deep = arguments[0]; - i++; - } + var extended = {}; + var deep = false; + var i = 0; + var length = arguments.length; + + // Check if a deep merge + if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') { + deep = arguments[0]; + i++; + } - // Merge the object into the extended object - var merge = function (obj) { - for ( var prop in obj ) { - if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) { - // If deep merge and property is an object, merge properties - if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) { - extended[prop] = extend( true, extended[prop], obj[prop] ); - } else { - extended[prop] = obj[prop]; - } + // Merge the object into the extended object + var merge = function (obj) { + for (var prop in obj) { + if (Object.prototype.hasOwnProperty.call(obj, prop)) { + // If deep merge and property is an object, merge properties + if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') { + extended[prop] = extend(true, extended[prop], obj[prop]); + } else { + extended[prop] = obj[prop]; } } - }; - - // Loop through each object and conduct a merge - for ( ; i < length; i++ ) { - var obj = arguments[i]; - merge(obj); } - - return extended; - }; - /** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ - var getHeight = function ( elem ) { - return Math.max( elem.scrollHeight, elem.offsetHeight, elem.clientHeight ); - }; + // Loop through each object and conduct a merge + for (; i < length; i++) { + var obj = arguments[i]; + merge(obj); + } - /** - * Get the closest matching element up the DOM tree. - * @private - * @param {Element} elem Starting element - * @param {String} selector Selector to match against - * @return {Boolean|Element} Returns null if not match found - */ - var getClosest = function ( elem, selector ) { - - // Element.matches() polyfill - if (!Element.prototype.matches) { - Element.prototype.matches = - Element.prototype.matchesSelector || - Element.prototype.mozMatchesSelector || - Element.prototype.msMatchesSelector || - Element.prototype.oMatchesSelector || - Element.prototype.webkitMatchesSelector || - function(s) { - var matches = (this.document || this.ownerDocument).querySelectorAll(s), - i = matches.length; - while (--i >= 0 && matches.item(i) !== this) {} - return i > -1; - }; - } + return extended; + +}; + +/** + * Get the height of an element. + * @private + * @param {Node} elem The element to get the height of + * @return {Number} The element's height in pixels + */ +var getHeight = function (elem) { + return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); +}; + +/** + * Escape special characters for use with querySelector + * @private + * @param {String} id The anchor ID to escape + * @author Mathias Bynens + * @link https://github.com/mathiasbynens/CSS.escape + */ +var escapeCharacters = function (id) { + + // Remove leading hash + if (id.charAt(0) === '#') { + id = id.substr(1); + } - // Get closest match - for ( ; elem && elem !== document; elem = elem.parentNode ) { - if ( elem.matches( selector ) ) return elem; + var string = String(id); + var length = string.length; + var index = -1; + var codeUnit; + var result = ''; + var firstCodeUnit = string.charCodeAt(0); + while (++index < length) { + codeUnit = string.charCodeAt(index); + // Note: there’s no need to special-case astral symbols, surrogate + // pairs, or lone surrogates. + + // If the character is NULL (U+0000), then throw an + // `InvalidCharacterError` exception and terminate these steps. + if (codeUnit === 0x0000) { + throw new InvalidCharacterError( + 'Invalid character: the input contains U+0000.' + ); } - return null; - - }; - - /** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ - var escapeCharacters = function ( id ) { - - // Remove leading hash - if ( id.charAt(0) === '#' ) { - id = id.substr(1); + if ( + // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is + // U+007F, […] + (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || + // If the character is the first character and is in the range [0-9] + // (U+0030 to U+0039), […] + (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || + // If the character is the second character and is in the range [0-9] + // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] + ( + index === 1 && + codeUnit >= 0x0030 && codeUnit <= 0x0039 && + firstCodeUnit === 0x002D + ) + ) { + // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point + result += '\\' + codeUnit.toString(16) + ' '; + continue; } - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); - + // If the character is not handled by one of the above rules and is + // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or + // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to + // U+005A), or [a-z] (U+0061 to U+007A), […] + if ( + codeUnit >= 0x0080 || + codeUnit === 0x002D || + codeUnit === 0x005F || + codeUnit >= 0x0030 && codeUnit <= 0x0039 || + codeUnit >= 0x0041 && codeUnit <= 0x005A || + codeUnit >= 0x0061 && codeUnit <= 0x007A + ) { + // the character itself + result += string.charAt(index); + continue; } - return '#' + result; + // Otherwise, the escaped character. + // http://dev.w3.org/csswg/cssom/#escape-a-character + result += '\\' + string.charAt(index); - }; + } - /** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ - var easingPattern = function ( type, time ) { - var pattern; - if ( type === 'easeInQuad' ) pattern = time * time; // accelerating from zero velocity - if ( type === 'easeOutQuad' ) pattern = time * (2 - time); // decelerating to zero velocity - if ( type === 'easeInOutQuad' ) pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if ( type === 'easeInCubic' ) pattern = time * time * time; // accelerating from zero velocity - if ( type === 'easeOutCubic' ) pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if ( type === 'easeInQuart' ) pattern = time * time * time * time; // accelerating from zero velocity - if ( type === 'easeOutQuart' ) pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if ( type === 'easeInOutQuart' ) pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if ( type === 'easeInQuint' ) pattern = time * time * time * time * time; // accelerating from zero velocity - if ( type === 'easeOutQuint' ) pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration - }; + return '#' + result; + +}; + +/** + * Calculate the easing pattern + * @private + * @link https://gist.github.com/gre/1650294 + * @param {String} type Easing pattern + * @param {Number} time Time animation should take to complete + * @returns {Number} + */ +var easingPattern = function (type, time) { + var pattern; + if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity + if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity + if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration + if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity + if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity + 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 + if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity + if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration + if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity + 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 + return pattern || time; // no easing, no acceleration +}; + +/** + * Calculate how far to scroll + * @private + * @param {Element} anchor The anchor element to scroll to + * @param {Number} headerHeight Height of a fixed header, if any + * @param {Number} offset Number of pixels by which to offset scroll + * @returns {Number} + */ +var getEndLocation = function (anchor, headerHeight, offset) { + var location = 0; + if (anchor.offsetParent) { + do { + location += anchor.offsetTop; + anchor = anchor.offsetParent; + } while (anchor); + } + location = Math.max(location - headerHeight - offset, 0); + return Math.min(location, getDocumentHeight() - getViewportHeight()); +}; + +/** + * Determine the viewport's height + * @private + * @returns {Number} + */ +var getViewportHeight = function () { + return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); +}; + +/** + * Determine the document's height + * @private + * @returns {Number} + */ +var getDocumentHeight = function () { + return Math.max( + document.body.scrollHeight, document.documentElement.scrollHeight, + document.body.offsetHeight, document.documentElement.offsetHeight, + document.body.clientHeight, document.documentElement.clientHeight + ); +}; + +/** + * Convert data-options attribute into an object of key/value pairs + * @private + * @param {String} options Link-specific options as a data attribute string + * @returns {Object} + */ +var getDataOptions = function (options) { + return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); +}; + +/** + * Get the height of the fixed header + * @private + * @param {Node} header The header + * @return {Number} The height of the header + */ +var getHeaderHeight = function (header) { + return !header ? 0 : (getHeight(header) + header.offsetTop); +}; + +/** + * Bring the anchored element into focus + * @private + */ +var adjustFocus = function (anchor, endLocation, isNum) { + + // Don't run if scrolling to a number on the page + if (isNum) return; + + // Otherwise, bring anchor element into focus + anchor.focus(); + if (document.activeElement.id !== anchor.id) { + anchor.setAttribute('tabindex', '-1'); + anchor.focus(); + anchor.style.outline = 'none'; + } + root.scrollTo(0, endLocation); + +}; + +/** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} anchor The element or position to scroll to + * @param {Element} toggle The element that toggled the scroll event + * @param {Object} options + */ +smoothScroll.animateScroll = function (anchor, toggle, options) { + + // Options and overrides + var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); + var animateSettings = extend(settings || defaults, options || {}, overrides); // Merge user options with defaults + + // Selectors and variables + var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; + var anchorElem = isNum || !anchor.tagName ? null : anchor; + if (!isNum && !anchorElem) return; + var startLocation = root.pageYOffset; // Current location on the page + if (animateSettings.selectorHeader && !fixedHeader) { + // Get the fixed header if not already set + fixedHeader = document.querySelector(animateSettings.selectorHeader); + } + if (!headerHeight) { + // Get the height of a fixed header if one exists and not already set + headerHeight = getHeaderHeight(fixedHeader); + } + var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to + var distance = endLocation - startLocation; // distance to travel + var documentHeight = getDocumentHeight(); + var timeLapsed = 0; + var percentage, position; /** - * Calculate how far to scroll + * Stop the scroll animation when it reaches its target (or the bottom/top of page) * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} + * @param {Number} position Current position on the page + * @param {Number} endLocation Scroll to location + * @param {Number} animationInterval How much to scroll on this loop */ - var getEndLocation = function ( anchor, headerHeight, offset ) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); - }; + var stopAnimateScroll = function (position, endLocation, animationInterval) { + var currentLocation = root.pageYOffset; + if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - /** - * Determine the viewport's height - * @private - * @returns {Number} - */ - var getViewportHeight = function() { - return Math.max( document.documentElement.clientHeight, root.innerHeight || 0 ); - }; + // Clear the animation timer + clearInterval(animationInterval); - /** - * Determine the document's height - * @private - * @returns {Number} - */ - var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); - }; + // Bring the anchored element into focus + adjustFocus(anchor, endLocation, isNum); - /** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ - var getDataOptions = function ( options ) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse( options ); + // Run callback after animation complete + animateSettings.callback(anchor, toggle); + + } }; /** - * Get the height of the fixed header + * Loop scrolling animation * @private - * @param {Node} header The header - * @return {Number} The height of the header */ - var getHeaderHeight = function ( header ) { - return !header ? 0 : ( getHeight( header ) + header.offsetTop ); + var loopAnimateScroll = function () { + timeLapsed += 16; + percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); + percentage = (percentage > 1) ? 1 : percentage; + position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + root.scrollTo(0, Math.floor(position)); + stopAnimateScroll(position, endLocation, animationInterval); }; /** - * Bring the anchored element into focus + * Set interval timer * @private */ - var adjustFocus = function ( anchor, endLocation, isNum ) { - - // Don't run if scrolling to a number on the page - if ( isNum ) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if ( document.activeElement.id !== anchor.id ) { - anchor.setAttribute( 'tabindex', '-1' ); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo( 0 , endLocation ); - + var startAnimateScroll = function () { + clearInterval(animationInterval); + animationInterval = setInterval(loopAnimateScroll, 16); }; /** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 */ - smoothScroll.animateScroll = function ( anchor, toggle, options ) { - - // Options and overrides - var overrides = getDataOptions( toggle ? toggle.getAttribute('data-options') : null ); - var animateSettings = extend( settings || defaults, options || {}, overrides ); // Merge user options with defaults - - // Selectors and variables - var isNum = Object.prototype.toString.call( anchor ) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if ( !isNum && !anchorElem ) return; - var startLocation = root.pageYOffset; // Current location on the page - if ( animateSettings.selectorHeader && !fixedHeader ) { - // Get the fixed header if not already set - fixedHeader = document.querySelector( animateSettings.selectorHeader ); - } - if ( !headerHeight ) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight( fixedHeader ); - } - var endLocation = isNum ? anchor : getEndLocation( anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10) ); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function ( position, endLocation, animationInterval ) { - var currentLocation = root.pageYOffset; - if ( position == endLocation || currentLocation == endLocation || ( (root.innerHeight + currentLocation) >= documentHeight ) ) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus( anchor, endLocation, isNum ); - - // Run callback after animation complete - animateSettings.callback( anchor, toggle ); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = ( timeLapsed / parseInt(animateSettings.speed, 10) ); - percentage = ( percentage > 1 ) ? 1 : percentage; - position = startLocation + ( distance * easingPattern(animateSettings.easing, percentage) ); - root.scrollTo( 0, Math.floor(position) ); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if ( root.pageYOffset === 0 ) { - root.scrollTo( 0, 0 ); - } + if (root.pageYOffset === 0) { + root.scrollTo(0, 0); + } - // Start scrolling animation - startAnimateScroll(); + // Start scrolling animation + startAnimateScroll(); - }; +}; - /** - * Handle has change event - * @private - */ - var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters( decodeURIComponent( root.location.hash ) ); - } catch(e) { - hash = escapeCharacters( root.location.hash ); - } +/** + * Handle has change event + * @private + */ +var hashChangeHandler = function (event) { - // Only run if there's an anchor element to scroll to - if ( !anchor ) return; + // Get hash from URL + // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(root.location.hash)); + } catch (e) { + hash = escapeCharacters(root.location.hash); + } - // Reset the anchor element's ID - anchor.id = anchor.getAttribute( 'data-scroll-id' ); + // Only run if there's an anchor element to scroll to + if (!anchor) return; - // Scroll to the anchored content - smoothScroll.animateScroll( anchor, toggle ); + // Reset the anchor element's ID + anchor.id = anchor.getAttribute('data-scroll-id'); - // Reset anchor and toggle - anchor = null; - toggle = null; + // Scroll to the anchored content + smoothScroll.animateScroll(anchor, toggle); - }; + // Reset anchor and toggle + anchor = null; + toggle = null; - /** - * If smooth scroll element clicked, animate scroll - * @private - */ - var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if ( event.button !== 0 || event.metaKey || event.ctrlKey ) return; - - // Check if a smooth scroll link was clicked - toggle = getClosest( event.target, settings.selector ); - if ( !toggle || toggle.tagName.toLowerCase() !== 'a' ) return; - - // Only run if link is an anchor and points to the current page - if ( toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href) ) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters( decodeURIComponent( toggle.hash ) ); - } catch(e) { - hash = escapeCharacters( toggle.hash ); - } +}; - // If the hash is empty, scroll to the top of the page - if ( hash === '#' ) { +/** + * If smooth scroll element clicked, animate scroll + * @private + */ +var clickHandler = function (event) { - // Prevent default link behavior - event.preventDefault(); + // Don't run if right-click or command/control + click + if (event.button !== 0 || event.metaKey || event.ctrlKey) return; - // Set the anchored element - anchor = document.body; + // Check if a smooth scroll link was clicked + toggle = event.target.closest(settings.selector); + if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute( 'data-scroll-id', id ); - anchor.id = ''; + // Only run if link is an anchor and points to the current page + if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if ( root.location.hash.substring(1) === id ) { - hashChangeHandler(); - } else { - root.location.hash = id; - } + // Get the sanitized hash + // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); + // console.log(hash); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(toggle.hash)); + } catch (e) { + hash = escapeCharacters(toggle.hash); + } - return; + // If the hash is empty, scroll to the top of the page + if (hash === '#') { - } + // Prevent default link behavior + event.preventDefault(); - // Get the anchored element - anchor = document.querySelector( hash ); + // Set the anchored element + anchor = document.body; - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if ( !anchor ) return; - anchor.setAttribute( 'data-scroll-id', anchor.id ); + // Save or create the ID as a data attribute and remove it (prevents scroll jump) + var id = anchor.id ? anchor.id : 'smooth-scroll-top'; + anchor.setAttribute('data-scroll-id', id); anchor.id = ''; // If no hash change event will happen, fire manually - if ( toggle.hash === root.location.hash ) { - event.preventDefault(); + // Otherwise, update the hash + if (root.location.hash.substring(1) === id) { hashChangeHandler(); + } else { + root.location.hash = id; } - }; - - /** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ - var resizeThrottler = function (event) { - if ( !eventTimeout ) { - eventTimeout = setTimeout(function() { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight( fixedHeader ); // Get the height of a fixed header if one exists - }, 66); - } - }; - - /** - * Destroy the current initialization. - * @public - */ - smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if ( !settings ) return; - - // Remove event listeners - document.removeEventListener( 'click', clickHandler, false ); - root.removeEventListener( 'resize', resizeThrottler, false ); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; - }; - - /** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ - smoothScroll.init = function ( options ) { - - // feature test - if ( !supports ) return; + return; - // Destroy any existing initializations - smoothScroll.destroy(); - - // Selectors and variables - settings = extend( defaults, options || {} ); // Merge user options with defaults - fixedHeader = settings.selectorHeader ? document.querySelector( settings.selectorHeader ) : null; // Get the fixed header - headerHeight = getHeaderHeight( fixedHeader ); + } - // When a toggle is clicked, run the click handler - document.addEventListener( 'click', clickHandler, false ); + // Get the anchored element + anchor = document.querySelector(hash); - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); + // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) + if (!anchor) return; + anchor.setAttribute('data-scroll-id', anchor.id); + anchor.id = ''; - // If window is resized and there's a fixed header, recalculate its size - if ( fixedHeader ) { - root.addEventListener( 'resize', resizeThrottler, false ); - } + // If no hash change event will happen, fire manually + if (toggle.hash === root.location.hash) { + event.preventDefault(); + hashChangeHandler(); + } - }; +}; + +/** + * On window scroll and resize, only run events at a rate of 15fps for better performance + * @private + * @param {Function} eventTimeout Timeout function + * @param {Object} settings + */ +var resizeThrottler = function (event) { + if (!eventTimeout) { + eventTimeout = setTimeout(function () { + eventTimeout = null; // Reset timeout + headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists + }, 66); + } +}; + +/** + * Destroy the current initialization. + * @public + */ +smoothScroll.destroy = function () { + + // If plugin isn't already initialized, stop + if (!settings) return; + + // Remove event listeners + document.removeEventListener('click', clickHandler, false); + root.removeEventListener('resize', resizeThrottler, false); + + // Reset varaibles + settings = null; + anchor = null; + toggle = null; + fixedHeader = null; + headerHeight = null; + eventTimeout = null; + animationInterval = null; +}; + +/** + * Initialize Smooth Scroll + * @public + * @param {Object} options User settings + */ +smoothScroll.init = function (options) { + + // feature test + if (!supports) return; + + // Destroy any existing initializations + smoothScroll.destroy(); + + // Selectors and variables + settings = extend(defaults, options || {}); // Merge user options with defaults + fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header + headerHeight = getHeaderHeight(fixedHeader); + + // When a toggle is clicked, run the click handler + document.addEventListener('click', clickHandler, false); + + // Listen for hash changes + root.addEventListener('hashchange', hashChangeHandler, false); + + // If window is resized and there's a fixed header, recalculate its size + if (fixedHeader) { + root.addEventListener('resize', resizeThrottler, false); + } +}; - // - // Public APIs - // - return smoothScroll; +// +// Public APIs +// -}); \ No newline at end of file +export default smoothScroll; \ No newline at end of file From 754eb76a3d340fb256b6525e190ff31eb3d7b1ac Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Sat, 29 Apr 2017 02:55:20 +0200 Subject: [PATCH 2/7] Remove extend. --- dist/js/smooth-scroll.js | 914 +++++++++++++----------------- dist/js/smooth-scroll.min.js | 488 +++++++++++++++- docs/dist/js/smooth-scroll.js | 914 +++++++++++++----------------- docs/dist/js/smooth-scroll.min.js | 488 +++++++++++++++- gulpfile.js | 6 +- src/js/smooth-scroll.js | 51 +- 6 files changed, 1799 insertions(+), 1062 deletions(-) diff --git a/dist/js/smooth-scroll.js b/dist/js/smooth-scroll.js index 3439579..aec335a 100755 --- a/dist/js/smooth-scroll.js +++ b/dist/js/smooth-scroll.js @@ -5,579 +5,483 @@ * http://github.com/cferdinandi/smooth-scroll */ -(function (root, factory) { - if ( typeof define === 'function' && define.amd ) { - define([], factory(root)); - } else if ( typeof exports === 'object' ) { - module.exports = factory(root); - } else { - root.smoothScroll = factory(root); - } -})(typeof global !== 'undefined' ? global : this.window || this.global, (function (root) { - - 'use strict'; - - // - // Variables - // - - var smoothScroll = {}; // Object for public APIs - var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test - var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - - // Default settings - var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () {} - }; - +var smoothScroll = {}; // Object for public APIs +var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test +var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; + +// Default settings +var defaults = { + selector: '[data-scroll]', + selectorHeader: null, + speed: 500, + easing: 'easeInOutCubic', + offset: 0, + callback: function () { } +}; + +// +// Methods +// + +/** + * Get the height of an element. + * @private + * @param {Node} elem The element to get the height of + * @return {Number} The element's height in pixels + */ +var getHeight = function (elem) { + return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); +}; + +/** + * Escape special characters for use with querySelector + * @private + * @param {String} id The anchor ID to escape + * @author Mathias Bynens + * @link https://github.com/mathiasbynens/CSS.escape + */ +var escapeCharacters = function (id) { - // - // Methods - // + // Remove leading hash + if (id.charAt(0) === '#') { + id = id.substr(1); + } - /** - * Merge two or more objects. Returns a new object. - * @private - * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] - * @param {Object} objects The objects to merge together - * @returns {Object} Merged values of defaults and options - */ - var extend = function () { - - // Variables - var extended = {}; - var deep = false; - var i = 0; - var length = arguments.length; - - // Check if a deep merge - if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) { - deep = arguments[0]; - i++; + var string = String(id); + var length = string.length; + var index = -1; + var codeUnit; + var result = ''; + var firstCodeUnit = string.charCodeAt(0); + while (++index < length) { + codeUnit = string.charCodeAt(index); + // Note: there’s no need to special-case astral symbols, surrogate + // pairs, or lone surrogates. + + // If the character is NULL (U+0000), then throw an + // `InvalidCharacterError` exception and terminate these steps. + if (codeUnit === 0x0000) { + throw new InvalidCharacterError( + 'Invalid character: the input contains U+0000.' + ); } - // Merge the object into the extended object - var merge = function (obj) { - for ( var prop in obj ) { - if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) { - // If deep merge and property is an object, merge properties - if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) { - extended[prop] = extend( true, extended[prop], obj[prop] ); - } else { - extended[prop] = obj[prop]; - } - } - } - }; - - // Loop through each object and conduct a merge - for ( ; i < length; i++ ) { - var obj = arguments[i]; - merge(obj); + if ( + // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is + // U+007F, […] + (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || + // If the character is the first character and is in the range [0-9] + // (U+0030 to U+0039), […] + (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || + // If the character is the second character and is in the range [0-9] + // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] + ( + index === 1 && + codeUnit >= 0x0030 && codeUnit <= 0x0039 && + firstCodeUnit === 0x002D + ) + ) { + // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point + result += '\\' + codeUnit.toString(16) + ' '; + continue; } - return extended; - - }; - - /** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ - var getHeight = function ( elem ) { - return Math.max( elem.scrollHeight, elem.offsetHeight, elem.clientHeight ); - }; - - /** - * Get the closest matching element up the DOM tree. - * @private - * @param {Element} elem Starting element - * @param {String} selector Selector to match against - * @return {Boolean|Element} Returns null if not match found - */ - var getClosest = function ( elem, selector ) { - - // Element.matches() polyfill - if (!Element.prototype.matches) { - Element.prototype.matches = - Element.prototype.matchesSelector || - Element.prototype.mozMatchesSelector || - Element.prototype.msMatchesSelector || - Element.prototype.oMatchesSelector || - Element.prototype.webkitMatchesSelector || - function(s) { - var matches = (this.document || this.ownerDocument).querySelectorAll(s), - i = matches.length; - while (--i >= 0 && matches.item(i) !== this) {} - return i > -1; - }; + // If the character is not handled by one of the above rules and is + // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or + // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to + // U+005A), or [a-z] (U+0061 to U+007A), […] + if ( + codeUnit >= 0x0080 || + codeUnit === 0x002D || + codeUnit === 0x005F || + codeUnit >= 0x0030 && codeUnit <= 0x0039 || + codeUnit >= 0x0041 && codeUnit <= 0x005A || + codeUnit >= 0x0061 && codeUnit <= 0x007A + ) { + // the character itself + result += string.charAt(index); + continue; } - // Get closest match - for ( ; elem && elem !== document; elem = elem.parentNode ) { - if ( elem.matches( selector ) ) return elem; - } + // Otherwise, the escaped character. + // http://dev.w3.org/csswg/cssom/#escape-a-character + result += '\\' + string.charAt(index); - return null; + } - }; + return '#' + result; - /** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ - var escapeCharacters = function ( id ) { +}; - // Remove leading hash - if ( id.charAt(0) === '#' ) { - id = id.substr(1); - } +/** + * Calculate the easing pattern + * @private + * @link https://gist.github.com/gre/1650294 + * @param {String} type Easing pattern + * @param {Number} time Time animation should take to complete + * @returns {Number} + */ +var easingPattern = function (type, time) { + var pattern; + if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity + if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity + if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration + if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity + if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity + 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 + if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity + if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration + if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity + 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 + return pattern || time; // no easing, no acceleration +}; + +/** + * Calculate how far to scroll + * @private + * @param {Element} anchor The anchor element to scroll to + * @param {Number} headerHeight Height of a fixed header, if any + * @param {Number} offset Number of pixels by which to offset scroll + * @returns {Number} + */ +var getEndLocation = function (anchor, headerHeight, offset) { + var location = 0; + if (anchor.offsetParent) { + do { + location += anchor.offsetTop; + anchor = anchor.offsetParent; + } while (anchor); + } + location = Math.max(location - headerHeight - offset, 0); + return Math.min(location, getDocumentHeight() - getViewportHeight()); +}; + +/** + * Determine the viewport's height + * @private + * @returns {Number} + */ +var getViewportHeight = function () { + return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); +}; + +/** + * Determine the document's height + * @private + * @returns {Number} + */ +var getDocumentHeight = function () { + return Math.max( + document.body.scrollHeight, document.documentElement.scrollHeight, + document.body.offsetHeight, document.documentElement.offsetHeight, + document.body.clientHeight, document.documentElement.clientHeight + ); +}; + +/** + * Convert data-options attribute into an object of key/value pairs + * @private + * @param {String} options Link-specific options as a data attribute string + * @returns {Object} + */ +var getDataOptions = function (options) { + return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); +}; + +/** + * Get the height of the fixed header + * @private + * @param {Node} header The header + * @return {Number} The height of the header + */ +var getHeaderHeight = function (header) { + return !header ? 0 : (getHeight(header) + header.offsetTop); +}; - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); +/** + * Bring the anchored element into focus + * @private + */ +var adjustFocus = function (anchor, endLocation, isNum) { - } + // Don't run if scrolling to a number on the page + if (isNum) return; - return '#' + result; + // Otherwise, bring anchor element into focus + anchor.focus(); + if (document.activeElement.id !== anchor.id) { + anchor.setAttribute('tabindex', '-1'); + anchor.focus(); + anchor.style.outline = 'none'; + } + root.scrollTo(0, endLocation); - }; +}; - /** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ - var easingPattern = function ( type, time ) { - var pattern; - if ( type === 'easeInQuad' ) pattern = time * time; // accelerating from zero velocity - if ( type === 'easeOutQuad' ) pattern = time * (2 - time); // decelerating to zero velocity - if ( type === 'easeInOutQuad' ) pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if ( type === 'easeInCubic' ) pattern = time * time * time; // accelerating from zero velocity - if ( type === 'easeOutCubic' ) pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if ( type === 'easeInQuart' ) pattern = time * time * time * time; // accelerating from zero velocity - if ( type === 'easeOutQuart' ) pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if ( type === 'easeInOutQuart' ) pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if ( type === 'easeInQuint' ) pattern = time * time * time * time * time; // accelerating from zero velocity - if ( type === 'easeOutQuint' ) pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration - }; +/** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} anchor The element or position to scroll to + * @param {Element} toggle The element that toggled the scroll event + * @param {Object} options + */ +smoothScroll.animateScroll = function (anchor, toggle, options) { + + // Options and overrides + var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); + var animateSettings = {}; + Object.assign(animateSettings, settings || defaults, options || {}, overrides); + + // Selectors and variables + var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; + var anchorElem = isNum || !anchor.tagName ? null : anchor; + if (!isNum && !anchorElem) return; + var startLocation = root.pageYOffset; // Current location on the page + if (animateSettings.selectorHeader && !fixedHeader) { + // Get the fixed header if not already set + fixedHeader = document.querySelector(animateSettings.selectorHeader); + } + if (!headerHeight) { + // Get the height of a fixed header if one exists and not already set + headerHeight = getHeaderHeight(fixedHeader); + } + var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to + var distance = endLocation - startLocation; // distance to travel + var documentHeight = getDocumentHeight(); + var timeLapsed = 0; + var percentage, position; /** - * Calculate how far to scroll + * Stop the scroll animation when it reaches its target (or the bottom/top of page) * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} + * @param {Number} position Current position on the page + * @param {Number} endLocation Scroll to location + * @param {Number} animationInterval How much to scroll on this loop */ - var getEndLocation = function ( anchor, headerHeight, offset ) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); - }; + var stopAnimateScroll = function (position, endLocation, animationInterval) { + var currentLocation = root.pageYOffset; + if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - /** - * Determine the viewport's height - * @private - * @returns {Number} - */ - var getViewportHeight = function() { - return Math.max( document.documentElement.clientHeight, root.innerHeight || 0 ); - }; + // Clear the animation timer + clearInterval(animationInterval); - /** - * Determine the document's height - * @private - * @returns {Number} - */ - var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); - }; + // Bring the anchored element into focus + adjustFocus(anchor, endLocation, isNum); - /** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ - var getDataOptions = function ( options ) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse( options ); + // Run callback after animation complete + animateSettings.callback(anchor, toggle); + + } }; /** - * Get the height of the fixed header + * Loop scrolling animation * @private - * @param {Node} header The header - * @return {Number} The height of the header */ - var getHeaderHeight = function ( header ) { - return !header ? 0 : ( getHeight( header ) + header.offsetTop ); + var loopAnimateScroll = function () { + timeLapsed += 16; + percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); + percentage = (percentage > 1) ? 1 : percentage; + position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + root.scrollTo(0, Math.floor(position)); + stopAnimateScroll(position, endLocation, animationInterval); }; /** - * Bring the anchored element into focus + * Set interval timer * @private */ - var adjustFocus = function ( anchor, endLocation, isNum ) { - - // Don't run if scrolling to a number on the page - if ( isNum ) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if ( document.activeElement.id !== anchor.id ) { - anchor.setAttribute( 'tabindex', '-1' ); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo( 0 , endLocation ); - + var startAnimateScroll = function () { + clearInterval(animationInterval); + animationInterval = setInterval(loopAnimateScroll, 16); }; /** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 */ - smoothScroll.animateScroll = function ( anchor, toggle, options ) { - - // Options and overrides - var overrides = getDataOptions( toggle ? toggle.getAttribute('data-options') : null ); - var animateSettings = extend( settings || defaults, options || {}, overrides ); // Merge user options with defaults - - // Selectors and variables - var isNum = Object.prototype.toString.call( anchor ) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if ( !isNum && !anchorElem ) return; - var startLocation = root.pageYOffset; // Current location on the page - if ( animateSettings.selectorHeader && !fixedHeader ) { - // Get the fixed header if not already set - fixedHeader = document.querySelector( animateSettings.selectorHeader ); - } - if ( !headerHeight ) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight( fixedHeader ); - } - var endLocation = isNum ? anchor : getEndLocation( anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10) ); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function ( position, endLocation, animationInterval ) { - var currentLocation = root.pageYOffset; - if ( position == endLocation || currentLocation == endLocation || ( (root.innerHeight + currentLocation) >= documentHeight ) ) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus( anchor, endLocation, isNum ); - - // Run callback after animation complete - animateSettings.callback( anchor, toggle ); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = ( timeLapsed / parseInt(animateSettings.speed, 10) ); - percentage = ( percentage > 1 ) ? 1 : percentage; - position = startLocation + ( distance * easingPattern(animateSettings.easing, percentage) ); - root.scrollTo( 0, Math.floor(position) ); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if ( root.pageYOffset === 0 ) { - root.scrollTo( 0, 0 ); - } - - // Start scrolling animation - startAnimateScroll(); - - }; - - /** - * Handle has change event - * @private - */ - var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters( decodeURIComponent( root.location.hash ) ); - } catch(e) { - hash = escapeCharacters( root.location.hash ); - } + if (root.pageYOffset === 0) { + root.scrollTo(0, 0); + } - // Only run if there's an anchor element to scroll to - if ( !anchor ) return; + // Start scrolling animation + startAnimateScroll(); - // Reset the anchor element's ID - anchor.id = anchor.getAttribute( 'data-scroll-id' ); +}; - // Scroll to the anchored content - smoothScroll.animateScroll( anchor, toggle ); +/** + * Handle has change event + * @private + */ +var hashChangeHandler = function (event) { + + // Get hash from URL + // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(root.location.hash)); + } catch (e) { + hash = escapeCharacters(root.location.hash); + } - // Reset anchor and toggle - anchor = null; - toggle = null; + // Only run if there's an anchor element to scroll to + if (!anchor) return; - }; + // Reset the anchor element's ID + anchor.id = anchor.getAttribute('data-scroll-id'); - /** - * If smooth scroll element clicked, animate scroll - * @private - */ - var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if ( event.button !== 0 || event.metaKey || event.ctrlKey ) return; - - // Check if a smooth scroll link was clicked - toggle = getClosest( event.target, settings.selector ); - if ( !toggle || toggle.tagName.toLowerCase() !== 'a' ) return; - - // Only run if link is an anchor and points to the current page - if ( toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href) ) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters( decodeURIComponent( toggle.hash ) ); - } catch(e) { - hash = escapeCharacters( toggle.hash ); - } + // Scroll to the anchored content + smoothScroll.animateScroll(anchor, toggle); - // If the hash is empty, scroll to the top of the page - if ( hash === '#' ) { + // Reset anchor and toggle + anchor = null; + toggle = null; - // Prevent default link behavior - event.preventDefault(); +}; - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute( 'data-scroll-id', id ); - anchor.id = ''; +/** + * If smooth scroll element clicked, animate scroll + * @private + */ +var clickHandler = function (event) { + + // Don't run if right-click or command/control + click + if (event.button !== 0 || event.metaKey || event.ctrlKey) return; + + // Check if a smooth scroll link was clicked + toggle = event.target.closest(settings.selector); + if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; + + // Only run if link is an anchor and points to the current page + if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; + + // Get the sanitized hash + // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); + // console.log(hash); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(toggle.hash)); + } catch (e) { + hash = escapeCharacters(toggle.hash); + } - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if ( root.location.hash.substring(1) === id ) { - hashChangeHandler(); - } else { - root.location.hash = id; - } + // If the hash is empty, scroll to the top of the page + if (hash === '#') { - return; + // Prevent default link behavior + event.preventDefault(); - } + // Set the anchored element + anchor = document.body; - // Get the anchored element - anchor = document.querySelector( hash ); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if ( !anchor ) return; - anchor.setAttribute( 'data-scroll-id', anchor.id ); + // Save or create the ID as a data attribute and remove it (prevents scroll jump) + var id = anchor.id ? anchor.id : 'smooth-scroll-top'; + anchor.setAttribute('data-scroll-id', id); anchor.id = ''; // If no hash change event will happen, fire manually - if ( toggle.hash === root.location.hash ) { - event.preventDefault(); + // Otherwise, update the hash + if (root.location.hash.substring(1) === id) { hashChangeHandler(); + } else { + root.location.hash = id; } - }; + return; - /** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ - var resizeThrottler = function (event) { - if ( !eventTimeout ) { - eventTimeout = setTimeout((function() { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight( fixedHeader ); // Get the height of a fixed header if one exists - }), 66); - } - }; + } - /** - * Destroy the current initialization. - * @public - */ - smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if ( !settings ) return; - - // Remove event listeners - document.removeEventListener( 'click', clickHandler, false ); - root.removeEventListener( 'resize', resizeThrottler, false ); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; - }; + // Get the anchored element + anchor = document.querySelector(hash); - /** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ - smoothScroll.init = function ( options ) { + // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) + if (!anchor) return; + anchor.setAttribute('data-scroll-id', anchor.id); + anchor.id = ''; + + // If no hash change event will happen, fire manually + if (toggle.hash === root.location.hash) { + event.preventDefault(); + hashChangeHandler(); + } + +}; + +/** + * On window scroll and resize, only run events at a rate of 15fps for better performance + * @private + * @param {Function} eventTimeout Timeout function + * @param {Object} settings + */ +var resizeThrottler = function (event) { + if (!eventTimeout) { + eventTimeout = setTimeout(function () { + eventTimeout = null; // Reset timeout + headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists + }, 66); + } +}; - // feature test - if ( !supports ) return; +/** + * Destroy the current initialization. + * @public + */ +smoothScroll.destroy = function () { + + // If plugin isn't already initialized, stop + if (!settings) return; + + // Remove event listeners + document.removeEventListener('click', clickHandler, false); + root.removeEventListener('resize', resizeThrottler, false); + + // Reset varaibles + settings = null; + anchor = null; + toggle = null; + fixedHeader = null; + headerHeight = null; + eventTimeout = null; + animationInterval = null; +}; + +/** + * Initialize Smooth Scroll + * @public + * @param {Object} options User settings + */ +smoothScroll.init = function (options) { - // Destroy any existing initializations - smoothScroll.destroy(); + // feature test + if (!supports) return; - // Selectors and variables - settings = extend( defaults, options || {} ); // Merge user options with defaults - fixedHeader = settings.selectorHeader ? document.querySelector( settings.selectorHeader ) : null; // Get the fixed header - headerHeight = getHeaderHeight( fixedHeader ); + // Destroy any existing initializations + smoothScroll.destroy(); - // When a toggle is clicked, run the click handler - document.addEventListener( 'click', clickHandler, false ); + // Selectors and variables + settings = {}; + Object.assign(settings, defaults, options || {}); + fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header + headerHeight = getHeaderHeight(fixedHeader); - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); + // When a toggle is clicked, run the click handler + document.addEventListener('click', clickHandler, false); - // If window is resized and there's a fixed header, recalculate its size - if ( fixedHeader ) { - root.addEventListener( 'resize', resizeThrottler, false ); - } + // Listen for hash changes + root.addEventListener('hashchange', hashChangeHandler, false); - }; + // If window is resized and there's a fixed header, recalculate its size + if (fixedHeader) { + root.addEventListener('resize', resizeThrottler, false); + } +}; - // - // Public APIs - // - return smoothScroll; +// +// Public APIs +// -})); \ No newline at end of file +export default smoothScroll; \ No newline at end of file diff --git a/dist/js/smooth-scroll.min.js b/dist/js/smooth-scroll.min.js index a01d8a3..f96421a 100755 --- a/dist/js/smooth-scroll.min.js +++ b/dist/js/smooth-scroll.min.js @@ -1,2 +1,488 @@ /*! smooth-scroll v10.3.1 | (c) 2017 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */ -!(function(e,t){"function"==typeof define&&define.amd?define([],t(e)):"object"==typeof exports?module.exports=t(e):e.smoothScroll=t(e)})("undefined"!=typeof global?global:this.window||this.global,(function(e){"use strict";var t,n,o,r,a,c,l,i={},u="querySelector"in document&&"addEventListener"in e,s={selector:"[data-scroll]",selectorHeader:null,speed:500,easing:"easeInOutCubic",offset:0,callback:function(){}},f=function(){var e={},t=!1,n=0,o=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(t=arguments[0],n++);for(;n=0&&t.item(n)!==this;);return n>-1});e&&e!==document;e=e.parentNode)if(e.matches(t))return e;return null},m=function(e){"#"===e.charAt(0)&&(e=e.substr(1));for(var t,n=String(e),o=n.length,r=-1,a="",c=n.charCodeAt(0);++r=1&&t<=31||127==t||0===r&&t>=48&&t<=57||1===r&&t>=48&&t<=57&&45===c?"\\"+t.toString(16)+" ":t>=128||45===t||95===t||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122?n.charAt(r):"\\"+n.charAt(r)}return"#"+a},p=function(e,t){var n;return"easeInQuad"===e&&(n=t*t),"easeOutQuad"===e&&(n=t*(2-t)),"easeInOutQuad"===e&&(n=t<.5?2*t*t:(4-2*t)*t-1),"easeInCubic"===e&&(n=t*t*t),"easeOutCubic"===e&&(n=--t*t*t+1),"easeInOutCubic"===e&&(n=t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1),"easeInQuart"===e&&(n=t*t*t*t),"easeOutQuart"===e&&(n=1- --t*t*t*t),"easeInOutQuart"===e&&(n=t<.5?8*t*t*t*t:1-8*--t*t*t*t),"easeInQuint"===e&&(n=t*t*t*t*t),"easeOutQuint"===e&&(n=1+--t*t*t*t*t),"easeInOutQuint"===e&&(n=t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t),n||t},g=function(e,t,n){var o=0;if(e.offsetParent)do{o+=e.offsetTop,e=e.offsetParent}while(e);return o=Math.max(o-t-n,0),Math.min(o,y()-b())},b=function(){return Math.max(document.documentElement.clientHeight,e.innerHeight||0)},y=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)},v=function(e){return e&&"object"==typeof JSON&&"function"==typeof JSON.parse?JSON.parse(e):{}},O=function(e){return e?d(e)+e.offsetTop:0},S=function(t,n,o){o||(t.focus(),document.activeElement.id!==t.id&&(t.setAttribute("tabindex","-1"),t.focus(),t.style.outline="none"),e.scrollTo(0,n))};i.animateScroll=function(n,o,c){var i=v(o?o.getAttribute("data-options"):null),u=f(t||s,c||{},i),d="[object Number]"===Object.prototype.toString.call(n),h=d||!n.tagName?null:n;if(d||h){var m=e.pageYOffset;u.selectorHeader&&!r&&(r=document.querySelector(u.selectorHeader)),a||(a=O(r));var b,E,I=d?n:g(h,a,parseInt("function"==typeof u.offset?u.offset():u.offset,10)),H=I-m,A=y(),j=0,C=function(t,r,a){var c=e.pageYOffset;(t==r||c==r||e.innerHeight+c>=A)&&(clearInterval(a),S(n,r,d),u.callback(n,o))},M=function(){j+=16,b=j/parseInt(u.speed,10),b=b>1?1:b,E=m+H*p(u.easing,b),e.scrollTo(0,Math.floor(E)),C(E,I,l)};0===e.pageYOffset&&e.scrollTo(0,0),(function(){clearInterval(l),l=setInterval(M,16)})()}};var E=function(t){try{m(decodeURIComponent(e.location.hash))}catch(t){m(e.location.hash)}n&&(n.id=n.getAttribute("data-scroll-id"),i.animateScroll(n,o),n=null,o=null)},I=function(r){if(0===r.button&&!r.metaKey&&!r.ctrlKey&&(o=h(r.target,t.selector))&&"a"===o.tagName.toLowerCase()&&o.hostname===e.location.hostname&&o.pathname===e.location.pathname&&/#/.test(o.href)){var a;try{a=m(decodeURIComponent(o.hash))}catch(e){a=m(o.hash)}if("#"===a){r.preventDefault(),n=document.body;var c=n.id?n.id:"smooth-scroll-top";return n.setAttribute("data-scroll-id",c),n.id="",void(e.location.hash.substring(1)===c?E():e.location.hash=c)}n=document.querySelector(a),n&&(n.setAttribute("data-scroll-id",n.id),n.id="",o.hash===e.location.hash&&(r.preventDefault(),E()))}},H=function(e){c||(c=setTimeout((function(){c=null,a=O(r)}),66))};return i.destroy=function(){t&&(document.removeEventListener("click",I,!1),e.removeEventListener("resize",H,!1),t=null,n=null,o=null,r=null,a=null,c=null,l=null)},i.init=function(n){u&&(i.destroy(),t=f(s,n||{}),r=t.selectorHeader?document.querySelector(t.selectorHeader):null,a=O(r),document.addEventListener("click",I,!1),e.addEventListener("hashchange",E,!1),r&&e.addEventListener("resize",H,!1))},i})); \ No newline at end of file +/*! + * smooth-scroll v10.3.1: Animate scrolling to anchor links + * (c) 2017 Chris Ferdinandi + * MIT License + * http://github.com/cferdinandi/smooth-scroll + */ + +var smoothScroll = {}; // Object for public APIs +var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test +var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; + +// Default settings +var defaults = { + selector: '[data-scroll]', + selectorHeader: null, + speed: 500, + easing: 'easeInOutCubic', + offset: 0, + callback: function () { } +}; + +// +// Methods +// + +/** + * Get the height of an element. + * @private + * @param {Node} elem The element to get the height of + * @return {Number} The element's height in pixels + */ +var getHeight = function (elem) { + return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); +}; + +/** + * Escape special characters for use with querySelector + * @private + * @param {String} id The anchor ID to escape + * @author Mathias Bynens + * @link https://github.com/mathiasbynens/CSS.escape + */ +var escapeCharacters = function (id) { + + // Remove leading hash + if (id.charAt(0) === '#') { + id = id.substr(1); + } + + var string = String(id); + var length = string.length; + var index = -1; + var codeUnit; + var result = ''; + var firstCodeUnit = string.charCodeAt(0); + while (++index < length) { + codeUnit = string.charCodeAt(index); + // Note: there’s no need to special-case astral symbols, surrogate + // pairs, or lone surrogates. + + // If the character is NULL (U+0000), then throw an + // `InvalidCharacterError` exception and terminate these steps. + if (codeUnit === 0x0000) { + throw new InvalidCharacterError( + 'Invalid character: the input contains U+0000.' + ); + } + + if ( + // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is + // U+007F, […] + (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || + // If the character is the first character and is in the range [0-9] + // (U+0030 to U+0039), […] + (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || + // If the character is the second character and is in the range [0-9] + // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] + ( + index === 1 && + codeUnit >= 0x0030 && codeUnit <= 0x0039 && + firstCodeUnit === 0x002D + ) + ) { + // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point + result += '\\' + codeUnit.toString(16) + ' '; + continue; + } + + // If the character is not handled by one of the above rules and is + // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or + // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to + // U+005A), or [a-z] (U+0061 to U+007A), […] + if ( + codeUnit >= 0x0080 || + codeUnit === 0x002D || + codeUnit === 0x005F || + codeUnit >= 0x0030 && codeUnit <= 0x0039 || + codeUnit >= 0x0041 && codeUnit <= 0x005A || + codeUnit >= 0x0061 && codeUnit <= 0x007A + ) { + // the character itself + result += string.charAt(index); + continue; + } + + // Otherwise, the escaped character. + // http://dev.w3.org/csswg/cssom/#escape-a-character + result += '\\' + string.charAt(index); + + } + + return '#' + result; + +}; + +/** + * Calculate the easing pattern + * @private + * @link https://gist.github.com/gre/1650294 + * @param {String} type Easing pattern + * @param {Number} time Time animation should take to complete + * @returns {Number} + */ +var easingPattern = function (type, time) { + var pattern; + if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity + if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity + if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration + if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity + if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity + 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 + if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity + if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration + if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity + 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 + return pattern || time; // no easing, no acceleration +}; + +/** + * Calculate how far to scroll + * @private + * @param {Element} anchor The anchor element to scroll to + * @param {Number} headerHeight Height of a fixed header, if any + * @param {Number} offset Number of pixels by which to offset scroll + * @returns {Number} + */ +var getEndLocation = function (anchor, headerHeight, offset) { + var location = 0; + if (anchor.offsetParent) { + do { + location += anchor.offsetTop; + anchor = anchor.offsetParent; + } while (anchor); + } + location = Math.max(location - headerHeight - offset, 0); + return Math.min(location, getDocumentHeight() - getViewportHeight()); +}; + +/** + * Determine the viewport's height + * @private + * @returns {Number} + */ +var getViewportHeight = function () { + return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); +}; + +/** + * Determine the document's height + * @private + * @returns {Number} + */ +var getDocumentHeight = function () { + return Math.max( + document.body.scrollHeight, document.documentElement.scrollHeight, + document.body.offsetHeight, document.documentElement.offsetHeight, + document.body.clientHeight, document.documentElement.clientHeight + ); +}; + +/** + * Convert data-options attribute into an object of key/value pairs + * @private + * @param {String} options Link-specific options as a data attribute string + * @returns {Object} + */ +var getDataOptions = function (options) { + return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); +}; + +/** + * Get the height of the fixed header + * @private + * @param {Node} header The header + * @return {Number} The height of the header + */ +var getHeaderHeight = function (header) { + return !header ? 0 : (getHeight(header) + header.offsetTop); +}; + +/** + * Bring the anchored element into focus + * @private + */ +var adjustFocus = function (anchor, endLocation, isNum) { + + // Don't run if scrolling to a number on the page + if (isNum) return; + + // Otherwise, bring anchor element into focus + anchor.focus(); + if (document.activeElement.id !== anchor.id) { + anchor.setAttribute('tabindex', '-1'); + anchor.focus(); + anchor.style.outline = 'none'; + } + root.scrollTo(0, endLocation); + +}; + +/** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} anchor The element or position to scroll to + * @param {Element} toggle The element that toggled the scroll event + * @param {Object} options + */ +smoothScroll.animateScroll = function (anchor, toggle, options) { + + // Options and overrides + var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); + var animateSettings = {}; + Object.assign(animateSettings, settings || defaults, options || {}, overrides); + + // Selectors and variables + var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; + var anchorElem = isNum || !anchor.tagName ? null : anchor; + if (!isNum && !anchorElem) return; + var startLocation = root.pageYOffset; // Current location on the page + if (animateSettings.selectorHeader && !fixedHeader) { + // Get the fixed header if not already set + fixedHeader = document.querySelector(animateSettings.selectorHeader); + } + if (!headerHeight) { + // Get the height of a fixed header if one exists and not already set + headerHeight = getHeaderHeight(fixedHeader); + } + var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to + var distance = endLocation - startLocation; // distance to travel + var documentHeight = getDocumentHeight(); + var timeLapsed = 0; + var percentage, position; + + /** + * Stop the scroll animation when it reaches its target (or the bottom/top of page) + * @private + * @param {Number} position Current position on the page + * @param {Number} endLocation Scroll to location + * @param {Number} animationInterval How much to scroll on this loop + */ + var stopAnimateScroll = function (position, endLocation, animationInterval) { + var currentLocation = root.pageYOffset; + if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { + + // Clear the animation timer + clearInterval(animationInterval); + + // Bring the anchored element into focus + adjustFocus(anchor, endLocation, isNum); + + // Run callback after animation complete + animateSettings.callback(anchor, toggle); + + } + }; + + /** + * Loop scrolling animation + * @private + */ + var loopAnimateScroll = function () { + timeLapsed += 16; + percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); + percentage = (percentage > 1) ? 1 : percentage; + position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + root.scrollTo(0, Math.floor(position)); + stopAnimateScroll(position, endLocation, animationInterval); + }; + + /** + * Set interval timer + * @private + */ + var startAnimateScroll = function () { + clearInterval(animationInterval); + animationInterval = setInterval(loopAnimateScroll, 16); + }; + + /** + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 + */ + if (root.pageYOffset === 0) { + root.scrollTo(0, 0); + } + + // Start scrolling animation + startAnimateScroll(); + +}; + +/** + * Handle has change event + * @private + */ +var hashChangeHandler = function (event) { + + // Get hash from URL + // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(root.location.hash)); + } catch (e) { + hash = escapeCharacters(root.location.hash); + } + + // Only run if there's an anchor element to scroll to + if (!anchor) return; + + // Reset the anchor element's ID + anchor.id = anchor.getAttribute('data-scroll-id'); + + // Scroll to the anchored content + smoothScroll.animateScroll(anchor, toggle); + + // Reset anchor and toggle + anchor = null; + toggle = null; + +}; + +/** + * If smooth scroll element clicked, animate scroll + * @private + */ +var clickHandler = function (event) { + + // Don't run if right-click or command/control + click + if (event.button !== 0 || event.metaKey || event.ctrlKey) return; + + // Check if a smooth scroll link was clicked + toggle = event.target.closest(settings.selector); + if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; + + // Only run if link is an anchor and points to the current page + if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; + + // Get the sanitized hash + // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); + // console.log(hash); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(toggle.hash)); + } catch (e) { + hash = escapeCharacters(toggle.hash); + } + + // If the hash is empty, scroll to the top of the page + if (hash === '#') { + + // Prevent default link behavior + event.preventDefault(); + + // Set the anchored element + anchor = document.body; + + // Save or create the ID as a data attribute and remove it (prevents scroll jump) + var id = anchor.id ? anchor.id : 'smooth-scroll-top'; + anchor.setAttribute('data-scroll-id', id); + anchor.id = ''; + + // If no hash change event will happen, fire manually + // Otherwise, update the hash + if (root.location.hash.substring(1) === id) { + hashChangeHandler(); + } else { + root.location.hash = id; + } + + return; + + } + + // Get the anchored element + anchor = document.querySelector(hash); + + // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) + if (!anchor) return; + anchor.setAttribute('data-scroll-id', anchor.id); + anchor.id = ''; + + // If no hash change event will happen, fire manually + if (toggle.hash === root.location.hash) { + event.preventDefault(); + hashChangeHandler(); + } + +}; + +/** + * On window scroll and resize, only run events at a rate of 15fps for better performance + * @private + * @param {Function} eventTimeout Timeout function + * @param {Object} settings + */ +var resizeThrottler = function (event) { + if (!eventTimeout) { + eventTimeout = setTimeout(function () { + eventTimeout = null; // Reset timeout + headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists + }, 66); + } +}; + +/** + * Destroy the current initialization. + * @public + */ +smoothScroll.destroy = function () { + + // If plugin isn't already initialized, stop + if (!settings) return; + + // Remove event listeners + document.removeEventListener('click', clickHandler, false); + root.removeEventListener('resize', resizeThrottler, false); + + // Reset varaibles + settings = null; + anchor = null; + toggle = null; + fixedHeader = null; + headerHeight = null; + eventTimeout = null; + animationInterval = null; +}; + +/** + * Initialize Smooth Scroll + * @public + * @param {Object} options User settings + */ +smoothScroll.init = function (options) { + + // feature test + if (!supports) return; + + // Destroy any existing initializations + smoothScroll.destroy(); + + // Selectors and variables + settings = {}; + Object.assign(settings, defaults, options || {}); + fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header + headerHeight = getHeaderHeight(fixedHeader); + + // When a toggle is clicked, run the click handler + document.addEventListener('click', clickHandler, false); + + // Listen for hash changes + root.addEventListener('hashchange', hashChangeHandler, false); + + // If window is resized and there's a fixed header, recalculate its size + if (fixedHeader) { + root.addEventListener('resize', resizeThrottler, false); + } + +}; + + +// +// Public APIs +// + +export default smoothScroll; \ No newline at end of file diff --git a/docs/dist/js/smooth-scroll.js b/docs/dist/js/smooth-scroll.js index 3439579..aec335a 100755 --- a/docs/dist/js/smooth-scroll.js +++ b/docs/dist/js/smooth-scroll.js @@ -5,579 +5,483 @@ * http://github.com/cferdinandi/smooth-scroll */ -(function (root, factory) { - if ( typeof define === 'function' && define.amd ) { - define([], factory(root)); - } else if ( typeof exports === 'object' ) { - module.exports = factory(root); - } else { - root.smoothScroll = factory(root); - } -})(typeof global !== 'undefined' ? global : this.window || this.global, (function (root) { - - 'use strict'; - - // - // Variables - // - - var smoothScroll = {}; // Object for public APIs - var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test - var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - - // Default settings - var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () {} - }; - +var smoothScroll = {}; // Object for public APIs +var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test +var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; + +// Default settings +var defaults = { + selector: '[data-scroll]', + selectorHeader: null, + speed: 500, + easing: 'easeInOutCubic', + offset: 0, + callback: function () { } +}; + +// +// Methods +// + +/** + * Get the height of an element. + * @private + * @param {Node} elem The element to get the height of + * @return {Number} The element's height in pixels + */ +var getHeight = function (elem) { + return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); +}; + +/** + * Escape special characters for use with querySelector + * @private + * @param {String} id The anchor ID to escape + * @author Mathias Bynens + * @link https://github.com/mathiasbynens/CSS.escape + */ +var escapeCharacters = function (id) { - // - // Methods - // + // Remove leading hash + if (id.charAt(0) === '#') { + id = id.substr(1); + } - /** - * Merge two or more objects. Returns a new object. - * @private - * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] - * @param {Object} objects The objects to merge together - * @returns {Object} Merged values of defaults and options - */ - var extend = function () { - - // Variables - var extended = {}; - var deep = false; - var i = 0; - var length = arguments.length; - - // Check if a deep merge - if ( Object.prototype.toString.call( arguments[0] ) === '[object Boolean]' ) { - deep = arguments[0]; - i++; + var string = String(id); + var length = string.length; + var index = -1; + var codeUnit; + var result = ''; + var firstCodeUnit = string.charCodeAt(0); + while (++index < length) { + codeUnit = string.charCodeAt(index); + // Note: there’s no need to special-case astral symbols, surrogate + // pairs, or lone surrogates. + + // If the character is NULL (U+0000), then throw an + // `InvalidCharacterError` exception and terminate these steps. + if (codeUnit === 0x0000) { + throw new InvalidCharacterError( + 'Invalid character: the input contains U+0000.' + ); } - // Merge the object into the extended object - var merge = function (obj) { - for ( var prop in obj ) { - if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) { - // If deep merge and property is an object, merge properties - if ( deep && Object.prototype.toString.call(obj[prop]) === '[object Object]' ) { - extended[prop] = extend( true, extended[prop], obj[prop] ); - } else { - extended[prop] = obj[prop]; - } - } - } - }; - - // Loop through each object and conduct a merge - for ( ; i < length; i++ ) { - var obj = arguments[i]; - merge(obj); + if ( + // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is + // U+007F, […] + (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || + // If the character is the first character and is in the range [0-9] + // (U+0030 to U+0039), […] + (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || + // If the character is the second character and is in the range [0-9] + // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] + ( + index === 1 && + codeUnit >= 0x0030 && codeUnit <= 0x0039 && + firstCodeUnit === 0x002D + ) + ) { + // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point + result += '\\' + codeUnit.toString(16) + ' '; + continue; } - return extended; - - }; - - /** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ - var getHeight = function ( elem ) { - return Math.max( elem.scrollHeight, elem.offsetHeight, elem.clientHeight ); - }; - - /** - * Get the closest matching element up the DOM tree. - * @private - * @param {Element} elem Starting element - * @param {String} selector Selector to match against - * @return {Boolean|Element} Returns null if not match found - */ - var getClosest = function ( elem, selector ) { - - // Element.matches() polyfill - if (!Element.prototype.matches) { - Element.prototype.matches = - Element.prototype.matchesSelector || - Element.prototype.mozMatchesSelector || - Element.prototype.msMatchesSelector || - Element.prototype.oMatchesSelector || - Element.prototype.webkitMatchesSelector || - function(s) { - var matches = (this.document || this.ownerDocument).querySelectorAll(s), - i = matches.length; - while (--i >= 0 && matches.item(i) !== this) {} - return i > -1; - }; + // If the character is not handled by one of the above rules and is + // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or + // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to + // U+005A), or [a-z] (U+0061 to U+007A), […] + if ( + codeUnit >= 0x0080 || + codeUnit === 0x002D || + codeUnit === 0x005F || + codeUnit >= 0x0030 && codeUnit <= 0x0039 || + codeUnit >= 0x0041 && codeUnit <= 0x005A || + codeUnit >= 0x0061 && codeUnit <= 0x007A + ) { + // the character itself + result += string.charAt(index); + continue; } - // Get closest match - for ( ; elem && elem !== document; elem = elem.parentNode ) { - if ( elem.matches( selector ) ) return elem; - } + // Otherwise, the escaped character. + // http://dev.w3.org/csswg/cssom/#escape-a-character + result += '\\' + string.charAt(index); - return null; + } - }; + return '#' + result; - /** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ - var escapeCharacters = function ( id ) { +}; - // Remove leading hash - if ( id.charAt(0) === '#' ) { - id = id.substr(1); - } +/** + * Calculate the easing pattern + * @private + * @link https://gist.github.com/gre/1650294 + * @param {String} type Easing pattern + * @param {Number} time Time animation should take to complete + * @returns {Number} + */ +var easingPattern = function (type, time) { + var pattern; + if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity + if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity + if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration + if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity + if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity + 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 + if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity + if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration + if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity + 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 + return pattern || time; // no easing, no acceleration +}; + +/** + * Calculate how far to scroll + * @private + * @param {Element} anchor The anchor element to scroll to + * @param {Number} headerHeight Height of a fixed header, if any + * @param {Number} offset Number of pixels by which to offset scroll + * @returns {Number} + */ +var getEndLocation = function (anchor, headerHeight, offset) { + var location = 0; + if (anchor.offsetParent) { + do { + location += anchor.offsetTop; + anchor = anchor.offsetParent; + } while (anchor); + } + location = Math.max(location - headerHeight - offset, 0); + return Math.min(location, getDocumentHeight() - getViewportHeight()); +}; + +/** + * Determine the viewport's height + * @private + * @returns {Number} + */ +var getViewportHeight = function () { + return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); +}; + +/** + * Determine the document's height + * @private + * @returns {Number} + */ +var getDocumentHeight = function () { + return Math.max( + document.body.scrollHeight, document.documentElement.scrollHeight, + document.body.offsetHeight, document.documentElement.offsetHeight, + document.body.clientHeight, document.documentElement.clientHeight + ); +}; + +/** + * Convert data-options attribute into an object of key/value pairs + * @private + * @param {String} options Link-specific options as a data attribute string + * @returns {Object} + */ +var getDataOptions = function (options) { + return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); +}; + +/** + * Get the height of the fixed header + * @private + * @param {Node} header The header + * @return {Number} The height of the header + */ +var getHeaderHeight = function (header) { + return !header ? 0 : (getHeight(header) + header.offsetTop); +}; - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); +/** + * Bring the anchored element into focus + * @private + */ +var adjustFocus = function (anchor, endLocation, isNum) { - } + // Don't run if scrolling to a number on the page + if (isNum) return; - return '#' + result; + // Otherwise, bring anchor element into focus + anchor.focus(); + if (document.activeElement.id !== anchor.id) { + anchor.setAttribute('tabindex', '-1'); + anchor.focus(); + anchor.style.outline = 'none'; + } + root.scrollTo(0, endLocation); - }; +}; - /** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ - var easingPattern = function ( type, time ) { - var pattern; - if ( type === 'easeInQuad' ) pattern = time * time; // accelerating from zero velocity - if ( type === 'easeOutQuad' ) pattern = time * (2 - time); // decelerating to zero velocity - if ( type === 'easeInOutQuad' ) pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if ( type === 'easeInCubic' ) pattern = time * time * time; // accelerating from zero velocity - if ( type === 'easeOutCubic' ) pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if ( type === 'easeInQuart' ) pattern = time * time * time * time; // accelerating from zero velocity - if ( type === 'easeOutQuart' ) pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if ( type === 'easeInOutQuart' ) pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if ( type === 'easeInQuint' ) pattern = time * time * time * time * time; // accelerating from zero velocity - if ( type === 'easeOutQuint' ) pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration - }; +/** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} anchor The element or position to scroll to + * @param {Element} toggle The element that toggled the scroll event + * @param {Object} options + */ +smoothScroll.animateScroll = function (anchor, toggle, options) { + + // Options and overrides + var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); + var animateSettings = {}; + Object.assign(animateSettings, settings || defaults, options || {}, overrides); + + // Selectors and variables + var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; + var anchorElem = isNum || !anchor.tagName ? null : anchor; + if (!isNum && !anchorElem) return; + var startLocation = root.pageYOffset; // Current location on the page + if (animateSettings.selectorHeader && !fixedHeader) { + // Get the fixed header if not already set + fixedHeader = document.querySelector(animateSettings.selectorHeader); + } + if (!headerHeight) { + // Get the height of a fixed header if one exists and not already set + headerHeight = getHeaderHeight(fixedHeader); + } + var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to + var distance = endLocation - startLocation; // distance to travel + var documentHeight = getDocumentHeight(); + var timeLapsed = 0; + var percentage, position; /** - * Calculate how far to scroll + * Stop the scroll animation when it reaches its target (or the bottom/top of page) * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} + * @param {Number} position Current position on the page + * @param {Number} endLocation Scroll to location + * @param {Number} animationInterval How much to scroll on this loop */ - var getEndLocation = function ( anchor, headerHeight, offset ) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); - }; + var stopAnimateScroll = function (position, endLocation, animationInterval) { + var currentLocation = root.pageYOffset; + if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - /** - * Determine the viewport's height - * @private - * @returns {Number} - */ - var getViewportHeight = function() { - return Math.max( document.documentElement.clientHeight, root.innerHeight || 0 ); - }; + // Clear the animation timer + clearInterval(animationInterval); - /** - * Determine the document's height - * @private - * @returns {Number} - */ - var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); - }; + // Bring the anchored element into focus + adjustFocus(anchor, endLocation, isNum); - /** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ - var getDataOptions = function ( options ) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse( options ); + // Run callback after animation complete + animateSettings.callback(anchor, toggle); + + } }; /** - * Get the height of the fixed header + * Loop scrolling animation * @private - * @param {Node} header The header - * @return {Number} The height of the header */ - var getHeaderHeight = function ( header ) { - return !header ? 0 : ( getHeight( header ) + header.offsetTop ); + var loopAnimateScroll = function () { + timeLapsed += 16; + percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); + percentage = (percentage > 1) ? 1 : percentage; + position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + root.scrollTo(0, Math.floor(position)); + stopAnimateScroll(position, endLocation, animationInterval); }; /** - * Bring the anchored element into focus + * Set interval timer * @private */ - var adjustFocus = function ( anchor, endLocation, isNum ) { - - // Don't run if scrolling to a number on the page - if ( isNum ) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if ( document.activeElement.id !== anchor.id ) { - anchor.setAttribute( 'tabindex', '-1' ); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo( 0 , endLocation ); - + var startAnimateScroll = function () { + clearInterval(animationInterval); + animationInterval = setInterval(loopAnimateScroll, 16); }; /** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 */ - smoothScroll.animateScroll = function ( anchor, toggle, options ) { - - // Options and overrides - var overrides = getDataOptions( toggle ? toggle.getAttribute('data-options') : null ); - var animateSettings = extend( settings || defaults, options || {}, overrides ); // Merge user options with defaults - - // Selectors and variables - var isNum = Object.prototype.toString.call( anchor ) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if ( !isNum && !anchorElem ) return; - var startLocation = root.pageYOffset; // Current location on the page - if ( animateSettings.selectorHeader && !fixedHeader ) { - // Get the fixed header if not already set - fixedHeader = document.querySelector( animateSettings.selectorHeader ); - } - if ( !headerHeight ) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight( fixedHeader ); - } - var endLocation = isNum ? anchor : getEndLocation( anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10) ); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function ( position, endLocation, animationInterval ) { - var currentLocation = root.pageYOffset; - if ( position == endLocation || currentLocation == endLocation || ( (root.innerHeight + currentLocation) >= documentHeight ) ) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus( anchor, endLocation, isNum ); - - // Run callback after animation complete - animateSettings.callback( anchor, toggle ); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = ( timeLapsed / parseInt(animateSettings.speed, 10) ); - percentage = ( percentage > 1 ) ? 1 : percentage; - position = startLocation + ( distance * easingPattern(animateSettings.easing, percentage) ); - root.scrollTo( 0, Math.floor(position) ); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if ( root.pageYOffset === 0 ) { - root.scrollTo( 0, 0 ); - } - - // Start scrolling animation - startAnimateScroll(); - - }; - - /** - * Handle has change event - * @private - */ - var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters( decodeURIComponent( root.location.hash ) ); - } catch(e) { - hash = escapeCharacters( root.location.hash ); - } + if (root.pageYOffset === 0) { + root.scrollTo(0, 0); + } - // Only run if there's an anchor element to scroll to - if ( !anchor ) return; + // Start scrolling animation + startAnimateScroll(); - // Reset the anchor element's ID - anchor.id = anchor.getAttribute( 'data-scroll-id' ); +}; - // Scroll to the anchored content - smoothScroll.animateScroll( anchor, toggle ); +/** + * Handle has change event + * @private + */ +var hashChangeHandler = function (event) { + + // Get hash from URL + // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(root.location.hash)); + } catch (e) { + hash = escapeCharacters(root.location.hash); + } - // Reset anchor and toggle - anchor = null; - toggle = null; + // Only run if there's an anchor element to scroll to + if (!anchor) return; - }; + // Reset the anchor element's ID + anchor.id = anchor.getAttribute('data-scroll-id'); - /** - * If smooth scroll element clicked, animate scroll - * @private - */ - var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if ( event.button !== 0 || event.metaKey || event.ctrlKey ) return; - - // Check if a smooth scroll link was clicked - toggle = getClosest( event.target, settings.selector ); - if ( !toggle || toggle.tagName.toLowerCase() !== 'a' ) return; - - // Only run if link is an anchor and points to the current page - if ( toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href) ) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters( decodeURIComponent( toggle.hash ) ); - } catch(e) { - hash = escapeCharacters( toggle.hash ); - } + // Scroll to the anchored content + smoothScroll.animateScroll(anchor, toggle); - // If the hash is empty, scroll to the top of the page - if ( hash === '#' ) { + // Reset anchor and toggle + anchor = null; + toggle = null; - // Prevent default link behavior - event.preventDefault(); +}; - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute( 'data-scroll-id', id ); - anchor.id = ''; +/** + * If smooth scroll element clicked, animate scroll + * @private + */ +var clickHandler = function (event) { + + // Don't run if right-click or command/control + click + if (event.button !== 0 || event.metaKey || event.ctrlKey) return; + + // Check if a smooth scroll link was clicked + toggle = event.target.closest(settings.selector); + if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; + + // Only run if link is an anchor and points to the current page + if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; + + // Get the sanitized hash + // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); + // console.log(hash); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(toggle.hash)); + } catch (e) { + hash = escapeCharacters(toggle.hash); + } - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if ( root.location.hash.substring(1) === id ) { - hashChangeHandler(); - } else { - root.location.hash = id; - } + // If the hash is empty, scroll to the top of the page + if (hash === '#') { - return; + // Prevent default link behavior + event.preventDefault(); - } + // Set the anchored element + anchor = document.body; - // Get the anchored element - anchor = document.querySelector( hash ); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if ( !anchor ) return; - anchor.setAttribute( 'data-scroll-id', anchor.id ); + // Save or create the ID as a data attribute and remove it (prevents scroll jump) + var id = anchor.id ? anchor.id : 'smooth-scroll-top'; + anchor.setAttribute('data-scroll-id', id); anchor.id = ''; // If no hash change event will happen, fire manually - if ( toggle.hash === root.location.hash ) { - event.preventDefault(); + // Otherwise, update the hash + if (root.location.hash.substring(1) === id) { hashChangeHandler(); + } else { + root.location.hash = id; } - }; + return; - /** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ - var resizeThrottler = function (event) { - if ( !eventTimeout ) { - eventTimeout = setTimeout((function() { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight( fixedHeader ); // Get the height of a fixed header if one exists - }), 66); - } - }; + } - /** - * Destroy the current initialization. - * @public - */ - smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if ( !settings ) return; - - // Remove event listeners - document.removeEventListener( 'click', clickHandler, false ); - root.removeEventListener( 'resize', resizeThrottler, false ); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; - }; + // Get the anchored element + anchor = document.querySelector(hash); - /** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ - smoothScroll.init = function ( options ) { + // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) + if (!anchor) return; + anchor.setAttribute('data-scroll-id', anchor.id); + anchor.id = ''; + + // If no hash change event will happen, fire manually + if (toggle.hash === root.location.hash) { + event.preventDefault(); + hashChangeHandler(); + } + +}; + +/** + * On window scroll and resize, only run events at a rate of 15fps for better performance + * @private + * @param {Function} eventTimeout Timeout function + * @param {Object} settings + */ +var resizeThrottler = function (event) { + if (!eventTimeout) { + eventTimeout = setTimeout(function () { + eventTimeout = null; // Reset timeout + headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists + }, 66); + } +}; - // feature test - if ( !supports ) return; +/** + * Destroy the current initialization. + * @public + */ +smoothScroll.destroy = function () { + + // If plugin isn't already initialized, stop + if (!settings) return; + + // Remove event listeners + document.removeEventListener('click', clickHandler, false); + root.removeEventListener('resize', resizeThrottler, false); + + // Reset varaibles + settings = null; + anchor = null; + toggle = null; + fixedHeader = null; + headerHeight = null; + eventTimeout = null; + animationInterval = null; +}; + +/** + * Initialize Smooth Scroll + * @public + * @param {Object} options User settings + */ +smoothScroll.init = function (options) { - // Destroy any existing initializations - smoothScroll.destroy(); + // feature test + if (!supports) return; - // Selectors and variables - settings = extend( defaults, options || {} ); // Merge user options with defaults - fixedHeader = settings.selectorHeader ? document.querySelector( settings.selectorHeader ) : null; // Get the fixed header - headerHeight = getHeaderHeight( fixedHeader ); + // Destroy any existing initializations + smoothScroll.destroy(); - // When a toggle is clicked, run the click handler - document.addEventListener( 'click', clickHandler, false ); + // Selectors and variables + settings = {}; + Object.assign(settings, defaults, options || {}); + fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header + headerHeight = getHeaderHeight(fixedHeader); - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); + // When a toggle is clicked, run the click handler + document.addEventListener('click', clickHandler, false); - // If window is resized and there's a fixed header, recalculate its size - if ( fixedHeader ) { - root.addEventListener( 'resize', resizeThrottler, false ); - } + // Listen for hash changes + root.addEventListener('hashchange', hashChangeHandler, false); - }; + // If window is resized and there's a fixed header, recalculate its size + if (fixedHeader) { + root.addEventListener('resize', resizeThrottler, false); + } +}; - // - // Public APIs - // - return smoothScroll; +// +// Public APIs +// -})); \ No newline at end of file +export default smoothScroll; \ No newline at end of file diff --git a/docs/dist/js/smooth-scroll.min.js b/docs/dist/js/smooth-scroll.min.js index a01d8a3..f96421a 100755 --- a/docs/dist/js/smooth-scroll.min.js +++ b/docs/dist/js/smooth-scroll.min.js @@ -1,2 +1,488 @@ /*! smooth-scroll v10.3.1 | (c) 2017 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */ -!(function(e,t){"function"==typeof define&&define.amd?define([],t(e)):"object"==typeof exports?module.exports=t(e):e.smoothScroll=t(e)})("undefined"!=typeof global?global:this.window||this.global,(function(e){"use strict";var t,n,o,r,a,c,l,i={},u="querySelector"in document&&"addEventListener"in e,s={selector:"[data-scroll]",selectorHeader:null,speed:500,easing:"easeInOutCubic",offset:0,callback:function(){}},f=function(){var e={},t=!1,n=0,o=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(t=arguments[0],n++);for(;n=0&&t.item(n)!==this;);return n>-1});e&&e!==document;e=e.parentNode)if(e.matches(t))return e;return null},m=function(e){"#"===e.charAt(0)&&(e=e.substr(1));for(var t,n=String(e),o=n.length,r=-1,a="",c=n.charCodeAt(0);++r=1&&t<=31||127==t||0===r&&t>=48&&t<=57||1===r&&t>=48&&t<=57&&45===c?"\\"+t.toString(16)+" ":t>=128||45===t||95===t||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122?n.charAt(r):"\\"+n.charAt(r)}return"#"+a},p=function(e,t){var n;return"easeInQuad"===e&&(n=t*t),"easeOutQuad"===e&&(n=t*(2-t)),"easeInOutQuad"===e&&(n=t<.5?2*t*t:(4-2*t)*t-1),"easeInCubic"===e&&(n=t*t*t),"easeOutCubic"===e&&(n=--t*t*t+1),"easeInOutCubic"===e&&(n=t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1),"easeInQuart"===e&&(n=t*t*t*t),"easeOutQuart"===e&&(n=1- --t*t*t*t),"easeInOutQuart"===e&&(n=t<.5?8*t*t*t*t:1-8*--t*t*t*t),"easeInQuint"===e&&(n=t*t*t*t*t),"easeOutQuint"===e&&(n=1+--t*t*t*t*t),"easeInOutQuint"===e&&(n=t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t),n||t},g=function(e,t,n){var o=0;if(e.offsetParent)do{o+=e.offsetTop,e=e.offsetParent}while(e);return o=Math.max(o-t-n,0),Math.min(o,y()-b())},b=function(){return Math.max(document.documentElement.clientHeight,e.innerHeight||0)},y=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)},v=function(e){return e&&"object"==typeof JSON&&"function"==typeof JSON.parse?JSON.parse(e):{}},O=function(e){return e?d(e)+e.offsetTop:0},S=function(t,n,o){o||(t.focus(),document.activeElement.id!==t.id&&(t.setAttribute("tabindex","-1"),t.focus(),t.style.outline="none"),e.scrollTo(0,n))};i.animateScroll=function(n,o,c){var i=v(o?o.getAttribute("data-options"):null),u=f(t||s,c||{},i),d="[object Number]"===Object.prototype.toString.call(n),h=d||!n.tagName?null:n;if(d||h){var m=e.pageYOffset;u.selectorHeader&&!r&&(r=document.querySelector(u.selectorHeader)),a||(a=O(r));var b,E,I=d?n:g(h,a,parseInt("function"==typeof u.offset?u.offset():u.offset,10)),H=I-m,A=y(),j=0,C=function(t,r,a){var c=e.pageYOffset;(t==r||c==r||e.innerHeight+c>=A)&&(clearInterval(a),S(n,r,d),u.callback(n,o))},M=function(){j+=16,b=j/parseInt(u.speed,10),b=b>1?1:b,E=m+H*p(u.easing,b),e.scrollTo(0,Math.floor(E)),C(E,I,l)};0===e.pageYOffset&&e.scrollTo(0,0),(function(){clearInterval(l),l=setInterval(M,16)})()}};var E=function(t){try{m(decodeURIComponent(e.location.hash))}catch(t){m(e.location.hash)}n&&(n.id=n.getAttribute("data-scroll-id"),i.animateScroll(n,o),n=null,o=null)},I=function(r){if(0===r.button&&!r.metaKey&&!r.ctrlKey&&(o=h(r.target,t.selector))&&"a"===o.tagName.toLowerCase()&&o.hostname===e.location.hostname&&o.pathname===e.location.pathname&&/#/.test(o.href)){var a;try{a=m(decodeURIComponent(o.hash))}catch(e){a=m(o.hash)}if("#"===a){r.preventDefault(),n=document.body;var c=n.id?n.id:"smooth-scroll-top";return n.setAttribute("data-scroll-id",c),n.id="",void(e.location.hash.substring(1)===c?E():e.location.hash=c)}n=document.querySelector(a),n&&(n.setAttribute("data-scroll-id",n.id),n.id="",o.hash===e.location.hash&&(r.preventDefault(),E()))}},H=function(e){c||(c=setTimeout((function(){c=null,a=O(r)}),66))};return i.destroy=function(){t&&(document.removeEventListener("click",I,!1),e.removeEventListener("resize",H,!1),t=null,n=null,o=null,r=null,a=null,c=null,l=null)},i.init=function(n){u&&(i.destroy(),t=f(s,n||{}),r=t.selectorHeader?document.querySelector(t.selectorHeader):null,a=O(r),document.addEventListener("click",I,!1),e.addEventListener("hashchange",E,!1),r&&e.addEventListener("resize",H,!1))},i})); \ No newline at end of file +/*! + * smooth-scroll v10.3.1: Animate scrolling to anchor links + * (c) 2017 Chris Ferdinandi + * MIT License + * http://github.com/cferdinandi/smooth-scroll + */ + +var smoothScroll = {}; // Object for public APIs +var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test +var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; + +// Default settings +var defaults = { + selector: '[data-scroll]', + selectorHeader: null, + speed: 500, + easing: 'easeInOutCubic', + offset: 0, + callback: function () { } +}; + +// +// Methods +// + +/** + * Get the height of an element. + * @private + * @param {Node} elem The element to get the height of + * @return {Number} The element's height in pixels + */ +var getHeight = function (elem) { + return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); +}; + +/** + * Escape special characters for use with querySelector + * @private + * @param {String} id The anchor ID to escape + * @author Mathias Bynens + * @link https://github.com/mathiasbynens/CSS.escape + */ +var escapeCharacters = function (id) { + + // Remove leading hash + if (id.charAt(0) === '#') { + id = id.substr(1); + } + + var string = String(id); + var length = string.length; + var index = -1; + var codeUnit; + var result = ''; + var firstCodeUnit = string.charCodeAt(0); + while (++index < length) { + codeUnit = string.charCodeAt(index); + // Note: there’s no need to special-case astral symbols, surrogate + // pairs, or lone surrogates. + + // If the character is NULL (U+0000), then throw an + // `InvalidCharacterError` exception and terminate these steps. + if (codeUnit === 0x0000) { + throw new InvalidCharacterError( + 'Invalid character: the input contains U+0000.' + ); + } + + if ( + // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is + // U+007F, […] + (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || + // If the character is the first character and is in the range [0-9] + // (U+0030 to U+0039), […] + (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || + // If the character is the second character and is in the range [0-9] + // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] + ( + index === 1 && + codeUnit >= 0x0030 && codeUnit <= 0x0039 && + firstCodeUnit === 0x002D + ) + ) { + // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point + result += '\\' + codeUnit.toString(16) + ' '; + continue; + } + + // If the character is not handled by one of the above rules and is + // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or + // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to + // U+005A), or [a-z] (U+0061 to U+007A), […] + if ( + codeUnit >= 0x0080 || + codeUnit === 0x002D || + codeUnit === 0x005F || + codeUnit >= 0x0030 && codeUnit <= 0x0039 || + codeUnit >= 0x0041 && codeUnit <= 0x005A || + codeUnit >= 0x0061 && codeUnit <= 0x007A + ) { + // the character itself + result += string.charAt(index); + continue; + } + + // Otherwise, the escaped character. + // http://dev.w3.org/csswg/cssom/#escape-a-character + result += '\\' + string.charAt(index); + + } + + return '#' + result; + +}; + +/** + * Calculate the easing pattern + * @private + * @link https://gist.github.com/gre/1650294 + * @param {String} type Easing pattern + * @param {Number} time Time animation should take to complete + * @returns {Number} + */ +var easingPattern = function (type, time) { + var pattern; + if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity + if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity + if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration + if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity + if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity + 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 + if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity + if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration + if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity + if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity + 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 + return pattern || time; // no easing, no acceleration +}; + +/** + * Calculate how far to scroll + * @private + * @param {Element} anchor The anchor element to scroll to + * @param {Number} headerHeight Height of a fixed header, if any + * @param {Number} offset Number of pixels by which to offset scroll + * @returns {Number} + */ +var getEndLocation = function (anchor, headerHeight, offset) { + var location = 0; + if (anchor.offsetParent) { + do { + location += anchor.offsetTop; + anchor = anchor.offsetParent; + } while (anchor); + } + location = Math.max(location - headerHeight - offset, 0); + return Math.min(location, getDocumentHeight() - getViewportHeight()); +}; + +/** + * Determine the viewport's height + * @private + * @returns {Number} + */ +var getViewportHeight = function () { + return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); +}; + +/** + * Determine the document's height + * @private + * @returns {Number} + */ +var getDocumentHeight = function () { + return Math.max( + document.body.scrollHeight, document.documentElement.scrollHeight, + document.body.offsetHeight, document.documentElement.offsetHeight, + document.body.clientHeight, document.documentElement.clientHeight + ); +}; + +/** + * Convert data-options attribute into an object of key/value pairs + * @private + * @param {String} options Link-specific options as a data attribute string + * @returns {Object} + */ +var getDataOptions = function (options) { + return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); +}; + +/** + * Get the height of the fixed header + * @private + * @param {Node} header The header + * @return {Number} The height of the header + */ +var getHeaderHeight = function (header) { + return !header ? 0 : (getHeight(header) + header.offsetTop); +}; + +/** + * Bring the anchored element into focus + * @private + */ +var adjustFocus = function (anchor, endLocation, isNum) { + + // Don't run if scrolling to a number on the page + if (isNum) return; + + // Otherwise, bring anchor element into focus + anchor.focus(); + if (document.activeElement.id !== anchor.id) { + anchor.setAttribute('tabindex', '-1'); + anchor.focus(); + anchor.style.outline = 'none'; + } + root.scrollTo(0, endLocation); + +}; + +/** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} anchor The element or position to scroll to + * @param {Element} toggle The element that toggled the scroll event + * @param {Object} options + */ +smoothScroll.animateScroll = function (anchor, toggle, options) { + + // Options and overrides + var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); + var animateSettings = {}; + Object.assign(animateSettings, settings || defaults, options || {}, overrides); + + // Selectors and variables + var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; + var anchorElem = isNum || !anchor.tagName ? null : anchor; + if (!isNum && !anchorElem) return; + var startLocation = root.pageYOffset; // Current location on the page + if (animateSettings.selectorHeader && !fixedHeader) { + // Get the fixed header if not already set + fixedHeader = document.querySelector(animateSettings.selectorHeader); + } + if (!headerHeight) { + // Get the height of a fixed header if one exists and not already set + headerHeight = getHeaderHeight(fixedHeader); + } + var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to + var distance = endLocation - startLocation; // distance to travel + var documentHeight = getDocumentHeight(); + var timeLapsed = 0; + var percentage, position; + + /** + * Stop the scroll animation when it reaches its target (or the bottom/top of page) + * @private + * @param {Number} position Current position on the page + * @param {Number} endLocation Scroll to location + * @param {Number} animationInterval How much to scroll on this loop + */ + var stopAnimateScroll = function (position, endLocation, animationInterval) { + var currentLocation = root.pageYOffset; + if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { + + // Clear the animation timer + clearInterval(animationInterval); + + // Bring the anchored element into focus + adjustFocus(anchor, endLocation, isNum); + + // Run callback after animation complete + animateSettings.callback(anchor, toggle); + + } + }; + + /** + * Loop scrolling animation + * @private + */ + var loopAnimateScroll = function () { + timeLapsed += 16; + percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); + percentage = (percentage > 1) ? 1 : percentage; + position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + root.scrollTo(0, Math.floor(position)); + stopAnimateScroll(position, endLocation, animationInterval); + }; + + /** + * Set interval timer + * @private + */ + var startAnimateScroll = function () { + clearInterval(animationInterval); + animationInterval = setInterval(loopAnimateScroll, 16); + }; + + /** + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 + */ + if (root.pageYOffset === 0) { + root.scrollTo(0, 0); + } + + // Start scrolling animation + startAnimateScroll(); + +}; + +/** + * Handle has change event + * @private + */ +var hashChangeHandler = function (event) { + + // Get hash from URL + // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(root.location.hash)); + } catch (e) { + hash = escapeCharacters(root.location.hash); + } + + // Only run if there's an anchor element to scroll to + if (!anchor) return; + + // Reset the anchor element's ID + anchor.id = anchor.getAttribute('data-scroll-id'); + + // Scroll to the anchored content + smoothScroll.animateScroll(anchor, toggle); + + // Reset anchor and toggle + anchor = null; + toggle = null; + +}; + +/** + * If smooth scroll element clicked, animate scroll + * @private + */ +var clickHandler = function (event) { + + // Don't run if right-click or command/control + click + if (event.button !== 0 || event.metaKey || event.ctrlKey) return; + + // Check if a smooth scroll link was clicked + toggle = event.target.closest(settings.selector); + if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; + + // Only run if link is an anchor and points to the current page + if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; + + // Get the sanitized hash + // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); + // console.log(hash); + var hash; + try { + hash = escapeCharacters(decodeURIComponent(toggle.hash)); + } catch (e) { + hash = escapeCharacters(toggle.hash); + } + + // If the hash is empty, scroll to the top of the page + if (hash === '#') { + + // Prevent default link behavior + event.preventDefault(); + + // Set the anchored element + anchor = document.body; + + // Save or create the ID as a data attribute and remove it (prevents scroll jump) + var id = anchor.id ? anchor.id : 'smooth-scroll-top'; + anchor.setAttribute('data-scroll-id', id); + anchor.id = ''; + + // If no hash change event will happen, fire manually + // Otherwise, update the hash + if (root.location.hash.substring(1) === id) { + hashChangeHandler(); + } else { + root.location.hash = id; + } + + return; + + } + + // Get the anchored element + anchor = document.querySelector(hash); + + // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) + if (!anchor) return; + anchor.setAttribute('data-scroll-id', anchor.id); + anchor.id = ''; + + // If no hash change event will happen, fire manually + if (toggle.hash === root.location.hash) { + event.preventDefault(); + hashChangeHandler(); + } + +}; + +/** + * On window scroll and resize, only run events at a rate of 15fps for better performance + * @private + * @param {Function} eventTimeout Timeout function + * @param {Object} settings + */ +var resizeThrottler = function (event) { + if (!eventTimeout) { + eventTimeout = setTimeout(function () { + eventTimeout = null; // Reset timeout + headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists + }, 66); + } +}; + +/** + * Destroy the current initialization. + * @public + */ +smoothScroll.destroy = function () { + + // If plugin isn't already initialized, stop + if (!settings) return; + + // Remove event listeners + document.removeEventListener('click', clickHandler, false); + root.removeEventListener('resize', resizeThrottler, false); + + // Reset varaibles + settings = null; + anchor = null; + toggle = null; + fixedHeader = null; + headerHeight = null; + eventTimeout = null; + animationInterval = null; +}; + +/** + * Initialize Smooth Scroll + * @public + * @param {Object} options User settings + */ +smoothScroll.init = function (options) { + + // feature test + if (!supports) return; + + // Destroy any existing initializations + smoothScroll.destroy(); + + // Selectors and variables + settings = {}; + Object.assign(settings, defaults, options || {}); + fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header + headerHeight = getHeaderHeight(fixedHeader); + + // When a toggle is clicked, run the click handler + document.addEventListener('click', clickHandler, false); + + // Listen for hash changes + root.addEventListener('hashchange', hashChangeHandler, false); + + // If window is resized and there's a fixed header, recalculate its size + if (fixedHeader) { + root.addEventListener('resize', resizeThrottler, false); + } + +}; + + +// +// Public APIs +// + +export default smoothScroll; \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index 63be8c9..d2b1b38 100755 --- a/gulpfile.js +++ b/gulpfile.js @@ -79,11 +79,11 @@ var banner = { gulp.task('build:scripts', ['clean:dist'], function() { var jsTasks = lazypipe() .pipe(header, banner.full, { package : package }) - .pipe(optimizejs) + // .pipe(optimizejs) .pipe(gulp.dest, paths.scripts.output) .pipe(rename, { suffix: '.min' }) - .pipe(uglify) - .pipe(optimizejs) + // .pipe(uglify) + // .pipe(optimizejs) .pipe(header, banner.min, { package : package }) .pipe(gulp.dest, paths.scripts.output); diff --git a/src/js/smooth-scroll.js b/src/js/smooth-scroll.js index ffd8dd3..10c4773 100755 --- a/src/js/smooth-scroll.js +++ b/src/js/smooth-scroll.js @@ -16,51 +16,6 @@ var defaults = { // Methods // -/** - * Merge two or more objects. Returns a new object. - * @private - * @param {Boolean} deep If true, do a deep (or recursive) merge [optional] - * @param {Object} objects The objects to merge together - * @returns {Object} Merged values of defaults and options - */ -var extend = function () { - - // Variables - var extended = {}; - var deep = false; - var i = 0; - var length = arguments.length; - - // Check if a deep merge - if (Object.prototype.toString.call(arguments[0]) === '[object Boolean]') { - deep = arguments[0]; - i++; - } - - // Merge the object into the extended object - var merge = function (obj) { - for (var prop in obj) { - if (Object.prototype.hasOwnProperty.call(obj, prop)) { - // If deep merge and property is an object, merge properties - if (deep && Object.prototype.toString.call(obj[prop]) === '[object Object]') { - extended[prop] = extend(true, extended[prop], obj[prop]); - } else { - extended[prop] = obj[prop]; - } - } - } - }; - - // Loop through each object and conduct a merge - for (; i < length; i++) { - var obj = arguments[i]; - merge(obj); - } - - return extended; - -}; - /** * Get the height of an element. * @private @@ -269,7 +224,8 @@ smoothScroll.animateScroll = function (anchor, toggle, options) { // Options and overrides var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); - var animateSettings = extend(settings || defaults, options || {}, overrides); // Merge user options with defaults + var animateSettings = {}; + Object.assign(animateSettings, settings || defaults, options || {}, overrides); // Selectors and variables var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; @@ -498,7 +454,8 @@ smoothScroll.init = function (options) { smoothScroll.destroy(); // Selectors and variables - settings = extend(defaults, options || {}); // Merge user options with defaults + settings = {}; + Object.assign(settings, defaults, options || {}); fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header headerHeight = getHeaderHeight(fixedHeader); From 207f3196c15ed54b42912894ea0f3c8266eac480 Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Sat, 29 Apr 2017 03:15:45 +0200 Subject: [PATCH 3/7] Remove gulp, travis and other unnecessary stuff. --- .travis.yml | 6 - CONTRIBUTING.md | 39 --- dist/js/smooth-scroll.js | 487 ----------------------------- dist/js/smooth-scroll.min.js | 488 ------------------------------ docs/dist/js/smooth-scroll.js | 487 ----------------------------- docs/dist/js/smooth-scroll.min.js | 488 ------------------------------ docs/index.html | 99 ------ gulpfile.js | 199 ------------ index.html | 99 ++++++ package.json | 22 -- src/docs/_templates/_footer.html | 13 - src/docs/_templates/_header.html | 30 -- src/docs/index.md | 57 ---- src/js/smooth-scroll.js | 91 ------ 14 files changed, 99 insertions(+), 2506 deletions(-) delete mode 100755 .travis.yml delete mode 100755 CONTRIBUTING.md delete mode 100755 dist/js/smooth-scroll.js delete mode 100755 dist/js/smooth-scroll.min.js delete mode 100755 docs/dist/js/smooth-scroll.js delete mode 100755 docs/dist/js/smooth-scroll.min.js delete mode 100644 docs/index.html delete mode 100755 gulpfile.js create mode 100644 index.html delete mode 100644 src/docs/_templates/_footer.html delete mode 100644 src/docs/_templates/_header.html delete mode 100644 src/docs/index.md diff --git a/.travis.yml b/.travis.yml deleted file mode 100755 index 83be3c0..0000000 --- a/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - "0.10" -before_script: - - npm install -g gulp -script: gulp \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100755 index c3863d1..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,39 +0,0 @@ -# How to contribute - -I'm delighted that you're helping make this open source project better. Here are a few quick guidelines to make this an easier and better process for everyone. - - - -## Reporting a bug - -First, **make sure the bug hasn't already been reported** by searching GitHub's issues section. - -If no existing issue exists, go ahead and create one. **Please be sure to include all of the following:** - -1. A clear, descriptive title (ie. "A bug" is *not* a good title). -2. [A reduced test case.](https://css-tricks.com/reduced-test-cases/) In order to debug code issues, I need to see actual code in a browser. -3. The browser and OS that you're using. - - - -## Asking a question - -Before asking, please **make sure the question hasn't already been asked** by searching GitHub's issues section. - - - -## Submitting a Pull Request - -Please make sure your code meets the following code standards: - -- Camel case for JavaScript variables. -- [Object-Oriented CSS](http://www.slideshare.net/stubbornella/object-oriented-css) for CSS selectors. -- Favor readable code over brevity. The build process will reduce size, so opt for readability. (ex. `var navigation` is better than `var n`) -- Order CSS properties alphabetically. -- Hard tabs. - -Before submitting, make sure that you've: - -- Updated the version number using semantic versioning. -- Made your changes in the `src` folder. -- Run the Gulp build to compile, minify, and update version numbers into the `dist` folder. If you cannot do this, please note this in the Pull Request. \ No newline at end of file diff --git a/dist/js/smooth-scroll.js b/dist/js/smooth-scroll.js deleted file mode 100755 index aec335a..0000000 --- a/dist/js/smooth-scroll.js +++ /dev/null @@ -1,487 +0,0 @@ -/*! - * smooth-scroll v10.3.1: Animate scrolling to anchor links - * (c) 2017 Chris Ferdinandi - * MIT License - * http://github.com/cferdinandi/smooth-scroll - */ - -var smoothScroll = {}; // Object for public APIs -var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test -var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - -// Default settings -var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () { } -}; - -// -// Methods -// - -/** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ -var getHeight = function (elem) { - return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); -}; - -/** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ -var escapeCharacters = function (id) { - - // Remove leading hash - if (id.charAt(0) === '#') { - id = id.substr(1); - } - - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); - - } - - return '#' + result; - -}; - -/** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ -var easingPattern = function (type, time) { - var pattern; - if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity - if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity - if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity - if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration -}; - -/** - * Calculate how far to scroll - * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} - */ -var getEndLocation = function (anchor, headerHeight, offset) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); -}; - -/** - * Determine the viewport's height - * @private - * @returns {Number} - */ -var getViewportHeight = function () { - return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); -}; - -/** - * Determine the document's height - * @private - * @returns {Number} - */ -var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); -}; - -/** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ -var getDataOptions = function (options) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); -}; - -/** - * Get the height of the fixed header - * @private - * @param {Node} header The header - * @return {Number} The height of the header - */ -var getHeaderHeight = function (header) { - return !header ? 0 : (getHeight(header) + header.offsetTop); -}; - -/** - * Bring the anchored element into focus - * @private - */ -var adjustFocus = function (anchor, endLocation, isNum) { - - // Don't run if scrolling to a number on the page - if (isNum) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if (document.activeElement.id !== anchor.id) { - anchor.setAttribute('tabindex', '-1'); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo(0, endLocation); - -}; - -/** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options - */ -smoothScroll.animateScroll = function (anchor, toggle, options) { - - // Options and overrides - var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); - var animateSettings = {}; - Object.assign(animateSettings, settings || defaults, options || {}, overrides); - - // Selectors and variables - var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if (!isNum && !anchorElem) return; - var startLocation = root.pageYOffset; // Current location on the page - if (animateSettings.selectorHeader && !fixedHeader) { - // Get the fixed header if not already set - fixedHeader = document.querySelector(animateSettings.selectorHeader); - } - if (!headerHeight) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight(fixedHeader); - } - var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function (position, endLocation, animationInterval) { - var currentLocation = root.pageYOffset; - if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus(anchor, endLocation, isNum); - - // Run callback after animation complete - animateSettings.callback(anchor, toggle); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); - percentage = (percentage > 1) ? 1 : percentage; - position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); - root.scrollTo(0, Math.floor(position)); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if (root.pageYOffset === 0) { - root.scrollTo(0, 0); - } - - // Start scrolling animation - startAnimateScroll(); - -}; - -/** - * Handle has change event - * @private - */ -var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(root.location.hash)); - } catch (e) { - hash = escapeCharacters(root.location.hash); - } - - // Only run if there's an anchor element to scroll to - if (!anchor) return; - - // Reset the anchor element's ID - anchor.id = anchor.getAttribute('data-scroll-id'); - - // Scroll to the anchored content - smoothScroll.animateScroll(anchor, toggle); - - // Reset anchor and toggle - anchor = null; - toggle = null; - -}; - -/** - * If smooth scroll element clicked, animate scroll - * @private - */ -var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if (event.button !== 0 || event.metaKey || event.ctrlKey) return; - - // Check if a smooth scroll link was clicked - toggle = event.target.closest(settings.selector); - if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; - - // Only run if link is an anchor and points to the current page - if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(toggle.hash)); - } catch (e) { - hash = escapeCharacters(toggle.hash); - } - - // If the hash is empty, scroll to the top of the page - if (hash === '#') { - - // Prevent default link behavior - event.preventDefault(); - - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute('data-scroll-id', id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if (root.location.hash.substring(1) === id) { - hashChangeHandler(); - } else { - root.location.hash = id; - } - - return; - - } - - // Get the anchored element - anchor = document.querySelector(hash); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if (!anchor) return; - anchor.setAttribute('data-scroll-id', anchor.id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - if (toggle.hash === root.location.hash) { - event.preventDefault(); - hashChangeHandler(); - } - -}; - -/** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ -var resizeThrottler = function (event) { - if (!eventTimeout) { - eventTimeout = setTimeout(function () { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists - }, 66); - } -}; - -/** - * Destroy the current initialization. - * @public - */ -smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if (!settings) return; - - // Remove event listeners - document.removeEventListener('click', clickHandler, false); - root.removeEventListener('resize', resizeThrottler, false); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; -}; - -/** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ -smoothScroll.init = function (options) { - - // feature test - if (!supports) return; - - // Destroy any existing initializations - smoothScroll.destroy(); - - // Selectors and variables - settings = {}; - Object.assign(settings, defaults, options || {}); - fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header - headerHeight = getHeaderHeight(fixedHeader); - - // When a toggle is clicked, run the click handler - document.addEventListener('click', clickHandler, false); - - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); - - // If window is resized and there's a fixed header, recalculate its size - if (fixedHeader) { - root.addEventListener('resize', resizeThrottler, false); - } - -}; - - -// -// Public APIs -// - -export default smoothScroll; \ No newline at end of file diff --git a/dist/js/smooth-scroll.min.js b/dist/js/smooth-scroll.min.js deleted file mode 100755 index f96421a..0000000 --- a/dist/js/smooth-scroll.min.js +++ /dev/null @@ -1,488 +0,0 @@ -/*! smooth-scroll v10.3.1 | (c) 2017 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */ -/*! - * smooth-scroll v10.3.1: Animate scrolling to anchor links - * (c) 2017 Chris Ferdinandi - * MIT License - * http://github.com/cferdinandi/smooth-scroll - */ - -var smoothScroll = {}; // Object for public APIs -var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test -var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - -// Default settings -var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () { } -}; - -// -// Methods -// - -/** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ -var getHeight = function (elem) { - return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); -}; - -/** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ -var escapeCharacters = function (id) { - - // Remove leading hash - if (id.charAt(0) === '#') { - id = id.substr(1); - } - - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); - - } - - return '#' + result; - -}; - -/** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ -var easingPattern = function (type, time) { - var pattern; - if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity - if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity - if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity - if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration -}; - -/** - * Calculate how far to scroll - * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} - */ -var getEndLocation = function (anchor, headerHeight, offset) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); -}; - -/** - * Determine the viewport's height - * @private - * @returns {Number} - */ -var getViewportHeight = function () { - return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); -}; - -/** - * Determine the document's height - * @private - * @returns {Number} - */ -var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); -}; - -/** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ -var getDataOptions = function (options) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); -}; - -/** - * Get the height of the fixed header - * @private - * @param {Node} header The header - * @return {Number} The height of the header - */ -var getHeaderHeight = function (header) { - return !header ? 0 : (getHeight(header) + header.offsetTop); -}; - -/** - * Bring the anchored element into focus - * @private - */ -var adjustFocus = function (anchor, endLocation, isNum) { - - // Don't run if scrolling to a number on the page - if (isNum) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if (document.activeElement.id !== anchor.id) { - anchor.setAttribute('tabindex', '-1'); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo(0, endLocation); - -}; - -/** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options - */ -smoothScroll.animateScroll = function (anchor, toggle, options) { - - // Options and overrides - var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); - var animateSettings = {}; - Object.assign(animateSettings, settings || defaults, options || {}, overrides); - - // Selectors and variables - var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if (!isNum && !anchorElem) return; - var startLocation = root.pageYOffset; // Current location on the page - if (animateSettings.selectorHeader && !fixedHeader) { - // Get the fixed header if not already set - fixedHeader = document.querySelector(animateSettings.selectorHeader); - } - if (!headerHeight) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight(fixedHeader); - } - var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function (position, endLocation, animationInterval) { - var currentLocation = root.pageYOffset; - if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus(anchor, endLocation, isNum); - - // Run callback after animation complete - animateSettings.callback(anchor, toggle); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); - percentage = (percentage > 1) ? 1 : percentage; - position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); - root.scrollTo(0, Math.floor(position)); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if (root.pageYOffset === 0) { - root.scrollTo(0, 0); - } - - // Start scrolling animation - startAnimateScroll(); - -}; - -/** - * Handle has change event - * @private - */ -var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(root.location.hash)); - } catch (e) { - hash = escapeCharacters(root.location.hash); - } - - // Only run if there's an anchor element to scroll to - if (!anchor) return; - - // Reset the anchor element's ID - anchor.id = anchor.getAttribute('data-scroll-id'); - - // Scroll to the anchored content - smoothScroll.animateScroll(anchor, toggle); - - // Reset anchor and toggle - anchor = null; - toggle = null; - -}; - -/** - * If smooth scroll element clicked, animate scroll - * @private - */ -var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if (event.button !== 0 || event.metaKey || event.ctrlKey) return; - - // Check if a smooth scroll link was clicked - toggle = event.target.closest(settings.selector); - if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; - - // Only run if link is an anchor and points to the current page - if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(toggle.hash)); - } catch (e) { - hash = escapeCharacters(toggle.hash); - } - - // If the hash is empty, scroll to the top of the page - if (hash === '#') { - - // Prevent default link behavior - event.preventDefault(); - - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute('data-scroll-id', id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if (root.location.hash.substring(1) === id) { - hashChangeHandler(); - } else { - root.location.hash = id; - } - - return; - - } - - // Get the anchored element - anchor = document.querySelector(hash); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if (!anchor) return; - anchor.setAttribute('data-scroll-id', anchor.id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - if (toggle.hash === root.location.hash) { - event.preventDefault(); - hashChangeHandler(); - } - -}; - -/** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ -var resizeThrottler = function (event) { - if (!eventTimeout) { - eventTimeout = setTimeout(function () { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists - }, 66); - } -}; - -/** - * Destroy the current initialization. - * @public - */ -smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if (!settings) return; - - // Remove event listeners - document.removeEventListener('click', clickHandler, false); - root.removeEventListener('resize', resizeThrottler, false); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; -}; - -/** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ -smoothScroll.init = function (options) { - - // feature test - if (!supports) return; - - // Destroy any existing initializations - smoothScroll.destroy(); - - // Selectors and variables - settings = {}; - Object.assign(settings, defaults, options || {}); - fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header - headerHeight = getHeaderHeight(fixedHeader); - - // When a toggle is clicked, run the click handler - document.addEventListener('click', clickHandler, false); - - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); - - // If window is resized and there's a fixed header, recalculate its size - if (fixedHeader) { - root.addEventListener('resize', resizeThrottler, false); - } - -}; - - -// -// Public APIs -// - -export default smoothScroll; \ No newline at end of file diff --git a/docs/dist/js/smooth-scroll.js b/docs/dist/js/smooth-scroll.js deleted file mode 100755 index aec335a..0000000 --- a/docs/dist/js/smooth-scroll.js +++ /dev/null @@ -1,487 +0,0 @@ -/*! - * smooth-scroll v10.3.1: Animate scrolling to anchor links - * (c) 2017 Chris Ferdinandi - * MIT License - * http://github.com/cferdinandi/smooth-scroll - */ - -var smoothScroll = {}; // Object for public APIs -var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test -var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - -// Default settings -var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () { } -}; - -// -// Methods -// - -/** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ -var getHeight = function (elem) { - return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); -}; - -/** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ -var escapeCharacters = function (id) { - - // Remove leading hash - if (id.charAt(0) === '#') { - id = id.substr(1); - } - - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); - - } - - return '#' + result; - -}; - -/** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ -var easingPattern = function (type, time) { - var pattern; - if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity - if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity - if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity - if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration -}; - -/** - * Calculate how far to scroll - * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} - */ -var getEndLocation = function (anchor, headerHeight, offset) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); -}; - -/** - * Determine the viewport's height - * @private - * @returns {Number} - */ -var getViewportHeight = function () { - return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); -}; - -/** - * Determine the document's height - * @private - * @returns {Number} - */ -var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); -}; - -/** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ -var getDataOptions = function (options) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); -}; - -/** - * Get the height of the fixed header - * @private - * @param {Node} header The header - * @return {Number} The height of the header - */ -var getHeaderHeight = function (header) { - return !header ? 0 : (getHeight(header) + header.offsetTop); -}; - -/** - * Bring the anchored element into focus - * @private - */ -var adjustFocus = function (anchor, endLocation, isNum) { - - // Don't run if scrolling to a number on the page - if (isNum) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if (document.activeElement.id !== anchor.id) { - anchor.setAttribute('tabindex', '-1'); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo(0, endLocation); - -}; - -/** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options - */ -smoothScroll.animateScroll = function (anchor, toggle, options) { - - // Options and overrides - var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); - var animateSettings = {}; - Object.assign(animateSettings, settings || defaults, options || {}, overrides); - - // Selectors and variables - var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if (!isNum && !anchorElem) return; - var startLocation = root.pageYOffset; // Current location on the page - if (animateSettings.selectorHeader && !fixedHeader) { - // Get the fixed header if not already set - fixedHeader = document.querySelector(animateSettings.selectorHeader); - } - if (!headerHeight) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight(fixedHeader); - } - var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function (position, endLocation, animationInterval) { - var currentLocation = root.pageYOffset; - if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus(anchor, endLocation, isNum); - - // Run callback after animation complete - animateSettings.callback(anchor, toggle); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); - percentage = (percentage > 1) ? 1 : percentage; - position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); - root.scrollTo(0, Math.floor(position)); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if (root.pageYOffset === 0) { - root.scrollTo(0, 0); - } - - // Start scrolling animation - startAnimateScroll(); - -}; - -/** - * Handle has change event - * @private - */ -var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(root.location.hash)); - } catch (e) { - hash = escapeCharacters(root.location.hash); - } - - // Only run if there's an anchor element to scroll to - if (!anchor) return; - - // Reset the anchor element's ID - anchor.id = anchor.getAttribute('data-scroll-id'); - - // Scroll to the anchored content - smoothScroll.animateScroll(anchor, toggle); - - // Reset anchor and toggle - anchor = null; - toggle = null; - -}; - -/** - * If smooth scroll element clicked, animate scroll - * @private - */ -var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if (event.button !== 0 || event.metaKey || event.ctrlKey) return; - - // Check if a smooth scroll link was clicked - toggle = event.target.closest(settings.selector); - if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; - - // Only run if link is an anchor and points to the current page - if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(toggle.hash)); - } catch (e) { - hash = escapeCharacters(toggle.hash); - } - - // If the hash is empty, scroll to the top of the page - if (hash === '#') { - - // Prevent default link behavior - event.preventDefault(); - - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute('data-scroll-id', id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if (root.location.hash.substring(1) === id) { - hashChangeHandler(); - } else { - root.location.hash = id; - } - - return; - - } - - // Get the anchored element - anchor = document.querySelector(hash); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if (!anchor) return; - anchor.setAttribute('data-scroll-id', anchor.id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - if (toggle.hash === root.location.hash) { - event.preventDefault(); - hashChangeHandler(); - } - -}; - -/** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ -var resizeThrottler = function (event) { - if (!eventTimeout) { - eventTimeout = setTimeout(function () { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists - }, 66); - } -}; - -/** - * Destroy the current initialization. - * @public - */ -smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if (!settings) return; - - // Remove event listeners - document.removeEventListener('click', clickHandler, false); - root.removeEventListener('resize', resizeThrottler, false); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; -}; - -/** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ -smoothScroll.init = function (options) { - - // feature test - if (!supports) return; - - // Destroy any existing initializations - smoothScroll.destroy(); - - // Selectors and variables - settings = {}; - Object.assign(settings, defaults, options || {}); - fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header - headerHeight = getHeaderHeight(fixedHeader); - - // When a toggle is clicked, run the click handler - document.addEventListener('click', clickHandler, false); - - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); - - // If window is resized and there's a fixed header, recalculate its size - if (fixedHeader) { - root.addEventListener('resize', resizeThrottler, false); - } - -}; - - -// -// Public APIs -// - -export default smoothScroll; \ No newline at end of file diff --git a/docs/dist/js/smooth-scroll.min.js b/docs/dist/js/smooth-scroll.min.js deleted file mode 100755 index f96421a..0000000 --- a/docs/dist/js/smooth-scroll.min.js +++ /dev/null @@ -1,488 +0,0 @@ -/*! smooth-scroll v10.3.1 | (c) 2017 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */ -/*! - * smooth-scroll v10.3.1: Animate scrolling to anchor links - * (c) 2017 Chris Ferdinandi - * MIT License - * http://github.com/cferdinandi/smooth-scroll - */ - -var smoothScroll = {}; // Object for public APIs -var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test -var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; - -// Default settings -var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeInOutCubic', - offset: 0, - callback: function () { } -}; - -// -// Methods -// - -/** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ -var getHeight = function (elem) { - return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); -}; - -/** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ -var escapeCharacters = function (id) { - - // Remove leading hash - if (id.charAt(0) === '#') { - id = id.substr(1); - } - - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); - - } - - return '#' + result; - -}; - -/** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ -var easingPattern = function (type, time) { - var pattern; - if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity - if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity - if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration - if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity - if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 - return pattern || time; // no easing, no acceleration -}; - -/** - * Calculate how far to scroll - * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} - */ -var getEndLocation = function (anchor, headerHeight, offset) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); -}; - -/** - * Determine the viewport's height - * @private - * @returns {Number} - */ -var getViewportHeight = function () { - return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); -}; - -/** - * Determine the document's height - * @private - * @returns {Number} - */ -var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); -}; - -/** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ -var getDataOptions = function (options) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); -}; - -/** - * Get the height of the fixed header - * @private - * @param {Node} header The header - * @return {Number} The height of the header - */ -var getHeaderHeight = function (header) { - return !header ? 0 : (getHeight(header) + header.offsetTop); -}; - -/** - * Bring the anchored element into focus - * @private - */ -var adjustFocus = function (anchor, endLocation, isNum) { - - // Don't run if scrolling to a number on the page - if (isNum) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if (document.activeElement.id !== anchor.id) { - anchor.setAttribute('tabindex', '-1'); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo(0, endLocation); - -}; - -/** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options - */ -smoothScroll.animateScroll = function (anchor, toggle, options) { - - // Options and overrides - var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); - var animateSettings = {}; - Object.assign(animateSettings, settings || defaults, options || {}, overrides); - - // Selectors and variables - var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if (!isNum && !anchorElem) return; - var startLocation = root.pageYOffset; // Current location on the page - if (animateSettings.selectorHeader && !fixedHeader) { - // Get the fixed header if not already set - fixedHeader = document.querySelector(animateSettings.selectorHeader); - } - if (!headerHeight) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight(fixedHeader); - } - var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function (position, endLocation, animationInterval) { - var currentLocation = root.pageYOffset; - if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus(anchor, endLocation, isNum); - - // Run callback after animation complete - animateSettings.callback(anchor, toggle); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); - percentage = (percentage > 1) ? 1 : percentage; - position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); - root.scrollTo(0, Math.floor(position)); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if (root.pageYOffset === 0) { - root.scrollTo(0, 0); - } - - // Start scrolling animation - startAnimateScroll(); - -}; - -/** - * Handle has change event - * @private - */ -var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(root.location.hash)); - } catch (e) { - hash = escapeCharacters(root.location.hash); - } - - // Only run if there's an anchor element to scroll to - if (!anchor) return; - - // Reset the anchor element's ID - anchor.id = anchor.getAttribute('data-scroll-id'); - - // Scroll to the anchored content - smoothScroll.animateScroll(anchor, toggle); - - // Reset anchor and toggle - anchor = null; - toggle = null; - -}; - -/** - * If smooth scroll element clicked, animate scroll - * @private - */ -var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if (event.button !== 0 || event.metaKey || event.ctrlKey) return; - - // Check if a smooth scroll link was clicked - toggle = event.target.closest(settings.selector); - if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; - - // Only run if link is an anchor and points to the current page - if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; - - // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(toggle.hash)); - } catch (e) { - hash = escapeCharacters(toggle.hash); - } - - // If the hash is empty, scroll to the top of the page - if (hash === '#') { - - // Prevent default link behavior - event.preventDefault(); - - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute('data-scroll-id', id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if (root.location.hash.substring(1) === id) { - hashChangeHandler(); - } else { - root.location.hash = id; - } - - return; - - } - - // Get the anchored element - anchor = document.querySelector(hash); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if (!anchor) return; - anchor.setAttribute('data-scroll-id', anchor.id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - if (toggle.hash === root.location.hash) { - event.preventDefault(); - hashChangeHandler(); - } - -}; - -/** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ -var resizeThrottler = function (event) { - if (!eventTimeout) { - eventTimeout = setTimeout(function () { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists - }, 66); - } -}; - -/** - * Destroy the current initialization. - * @public - */ -smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if (!settings) return; - - // Remove event listeners - document.removeEventListener('click', clickHandler, false); - root.removeEventListener('resize', resizeThrottler, false); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; -}; - -/** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ -smoothScroll.init = function (options) { - - // feature test - if (!supports) return; - - // Destroy any existing initializations - smoothScroll.destroy(); - - // Selectors and variables - settings = {}; - Object.assign(settings, defaults, options || {}); - fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header - headerHeight = getHeaderHeight(fixedHeader); - - // When a toggle is clicked, run the click handler - document.addEventListener('click', clickHandler, false); - - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); - - // If window is resized and there's a fixed header, recalculate its size - if (fixedHeader) { - root.addEventListener('resize', resizeThrottler, false); - } - -}; - - -// -// Public APIs -// - -export default smoothScroll; \ No newline at end of file diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index e61cf7c..0000000 --- a/docs/index.html +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - Smooth Scroll - - - - - - - - -
- - - -
-

- Linear
- Linear (no other options)
-

- -

- Ease-In
- Quad
- Cubic
- Quart
- Quint -

- -

- Ease-In-Out
- Quad
- Cubic
- Quart
- Quint -

- -

- Ease-Out
- Quad
- Cubic
- Quart
- Quint -

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

- Non-ASCII Characters
- 中文 -

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

中文

- -

Bazinga!

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

Back to the top

-
-
- - - - - - - - \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100755 index d2b1b38..0000000 --- a/gulpfile.js +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Gulp Packages - */ - -// General -var gulp = require('gulp'); -var fs = require('fs'); -var del = require('del'); -var lazypipe = require('lazypipe'); -var plumber = require('gulp-plumber'); -var flatten = require('gulp-flatten'); -var tap = require('gulp-tap'); -var rename = require('gulp-rename'); -var header = require('gulp-header'); -var footer = require('gulp-footer'); -var watch = require('gulp-watch'); -var livereload = require('gulp-livereload'); -var package = require('./package.json'); - -// Scripts and tests -var jshint = require('gulp-jshint'); -var stylish = require('jshint-stylish'); -var concat = require('gulp-concat'); -var uglify = require('gulp-uglify'); -var optimizejs = require('gulp-optimize-js'); - -// Docs -var markdown = require('gulp-markdown'); -var fileinclude = require('gulp-file-include'); - - -/** - * Paths to project folders - */ - -var paths = { - input: 'src/**/*', - output: 'dist/', - scripts: { - input: 'src/js/*', - output: 'dist/js/' - }, - docs: { - input: 'src/docs/*.{html,md,markdown}', - output: 'docs/', - templates: 'src/docs/_templates/', - assets: 'src/docs/assets/**' - } -}; - - -/** - * Template for banner to add to file headers - */ - -var banner = { - full : - '/*!\n' + - ' * <%= package.name %> v<%= package.version %>: <%= package.description %>\n' + - ' * (c) ' + new Date().getFullYear() + ' <%= package.author.name %>\n' + - ' * MIT License\n' + - ' * <%= package.repository.url %>\n' + - ' */\n\n', - min : - '/*!' + - ' <%= package.name %> v<%= package.version %>' + - ' | (c) ' + new Date().getFullYear() + ' <%= package.author.name %>' + - ' | MIT License' + - ' | <%= package.repository.url %>' + - ' */\n' -}; - - -/** - * Gulp Taks - */ - -// Lint, minify, and concatenate scripts -gulp.task('build:scripts', ['clean:dist'], function() { - var jsTasks = lazypipe() - .pipe(header, banner.full, { package : package }) - // .pipe(optimizejs) - .pipe(gulp.dest, paths.scripts.output) - .pipe(rename, { suffix: '.min' }) - // .pipe(uglify) - // .pipe(optimizejs) - .pipe(header, banner.min, { package : package }) - .pipe(gulp.dest, paths.scripts.output); - - return gulp.src(paths.scripts.input) - .pipe(plumber()) - .pipe(tap(function (file, t) { - if ( file.isDirectory() ) { - var name = file.relative + '.js'; - return gulp.src(file.path + '/*.js') - .pipe(concat(name)) - .pipe(jsTasks()); - } - })) - .pipe(jsTasks()); -}); - -// Lint scripts -gulp.task('lint:scripts', function () { - return gulp.src(paths.scripts.input) - .pipe(plumber()) - .pipe(jshint()) - .pipe(jshint.reporter('jshint-stylish')); -}); - -// Remove pre-existing content from output folders -gulp.task('clean:dist', function () { - del.sync([ - paths.output - ]); -}); - -// Generate documentation -gulp.task('build:docs', ['compile', 'clean:docs'], function() { - return gulp.src(paths.docs.input) - .pipe(plumber()) - .pipe(fileinclude({ - prefix: '@@', - basepath: '@file' - })) - .pipe(tap(function (file, t) { - if ( /\.md|\.markdown/.test(file.path) ) { - return t.through(markdown); - } - })) - .pipe(header(fs.readFileSync(paths.docs.templates + '/_header.html', 'utf8'))) - .pipe(footer(fs.readFileSync(paths.docs.templates + '/_footer.html', 'utf8'))) - .pipe(gulp.dest(paths.docs.output)); -}); - -// Copy distribution files to docs -gulp.task('copy:dist', ['compile', 'clean:docs'], function() { - return gulp.src(paths.output + '/**') - .pipe(plumber()) - .pipe(gulp.dest(paths.docs.output + '/dist')); -}); - -// Copy documentation assets to docs -gulp.task('copy:assets', ['clean:docs'], function() { - return gulp.src(paths.docs.assets) - .pipe(plumber()) - .pipe(gulp.dest(paths.docs.output + '/assets')); -}); - -// Remove prexisting content from docs folder -gulp.task('clean:docs', function () { - return del.sync(paths.docs.output); -}); - -// Spin up livereload server and listen for file changes -gulp.task('listen', function () { - livereload.listen(); - gulp.watch(paths.input).on('change', function(file) { - gulp.start('default'); - gulp.start('refresh'); - }); -}); - -// Run livereload after file change -gulp.task('refresh', ['compile', 'docs'], function () { - livereload.changed(); -}); - - -/** - * Task Runners - */ - -// Compile files -gulp.task('compile', [ - 'lint:scripts', - 'clean:dist', - 'build:scripts' -]); - -// Generate documentation -gulp.task('docs', [ - 'clean:docs', - 'build:docs', - 'copy:dist', - 'copy:assets' -]); - -// Compile files and generate docs (default) -gulp.task('default', [ - 'compile', - 'docs' -]); - -// Compile files and generate docs when something changes -gulp.task('watch', [ - 'listen', - 'default' -]); \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..11128dd --- /dev/null +++ b/index.html @@ -0,0 +1,99 @@ + + + + + + Smooth Scroll + + + + + + + + +
+ + + +
+

+ Linear
+ Linear (no other options)
+

+ +

+ Ease-In
+ Quad
+ Cubic
+ Quart
+ Quint +

+ +

+ Ease-In-Out
+ Quad
+ Cubic
+ Quart
+ Quint +

+ +

+ Ease-Out
+ Quad
+ Cubic
+ Quart
+ Quint +

+ +

+ .
.
.
.
.
.
.
.
.
.
.
.
.
+ .
.
.
.
.
.
.
.
.
.
.
.
.
+ .
.
.
.
.
.
.
.
.
.
.
.
. +

+ +

+ Non-ASCII Characters
+ 中文 +

+ +

+ .
.
.
.
.
.
.
.
.
.
.
.
.
+ .
.
.
.
.
.
.
.
.
.
.
.
.
+ .
.
.
.
.
.
.
.
.
.
.
.
. +

+ +

中文

+ +

Bazinga!

+ +

+ .
.
.
.
.
.
.
.
.
.
.
.
.
+ .
.
.
.
.
.
.
.
.
.
.
.
.
+ .
.
.
.
.
.
.
.
.
.
.
.
. +

+ +

Back to the top

+
+
+ + + + + + + + \ No newline at end of file diff --git a/package.json b/package.json index eca9e45..3de48af 100755 --- a/package.json +++ b/package.json @@ -11,27 +11,5 @@ "repository": { "type": "git", "url": "http://github.com/cferdinandi/smooth-scroll" - }, - "devDependencies": { - "gulp": "^3.9.1", - "node-fs": "^0.1.7", - "del": "^2.2.2", - "lazypipe": "^1.0.1", - "gulp-plumber": "^1.1.0", - "gulp-flatten": "^0.3.1", - "gulp-tap": "^0.1.3", - "gulp-rename": "^1.2.2", - "gulp-header": "^1.8.8", - "gulp-footer": "^1.0.5", - "gulp-watch": "^4.3.11", - "gulp-livereload": "^3.8.1", - "jshint": "^2.9.4", - "gulp-jshint": "^2.0.4", - "jshint-stylish": "^2.2.1", - "gulp-concat": "^2.6.1", - "gulp-uglify": "^2.1.2", - "gulp-optimize-js": "^1.1.0", - "gulp-markdown": "^1.2.0", - "gulp-file-include": "^0.14.0" } } diff --git a/src/docs/_templates/_footer.html b/src/docs/_templates/_footer.html deleted file mode 100644 index 81c0ea3..0000000 --- a/src/docs/_templates/_footer.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/src/docs/_templates/_header.html b/src/docs/_templates/_header.html deleted file mode 100644 index 2bd0e5c..0000000 --- a/src/docs/_templates/_header.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - Smooth Scroll - - - - - - - - -
- - - -
diff --git a/src/docs/index.md b/src/docs/index.md deleted file mode 100644 index e55a541..0000000 --- a/src/docs/index.md +++ /dev/null @@ -1,57 +0,0 @@ -

- Linear
- Linear (no other options)
-

- -

- Ease-In
- Quad
- Cubic
- Quart
- Quint -

- -

- Ease-In-Out
- Quad
- Cubic
- Quart
- Quint -

- -

- Ease-Out
- Quad
- Cubic
- Quart
- Quint -

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

- Non-ASCII Characters
- 中文 -

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

中文

- -

Bazinga!

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

Back to the top

\ No newline at end of file diff --git a/src/js/smooth-scroll.js b/src/js/smooth-scroll.js index 10c4773..62bfe38 100755 --- a/src/js/smooth-scroll.js +++ b/src/js/smooth-scroll.js @@ -26,86 +26,6 @@ var getHeight = function (elem) { return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); }; -/** - * Escape special characters for use with querySelector - * @private - * @param {String} id The anchor ID to escape - * @author Mathias Bynens - * @link https://github.com/mathiasbynens/CSS.escape - */ -var escapeCharacters = function (id) { - - // Remove leading hash - if (id.charAt(0) === '#') { - id = id.substr(1); - } - - var string = String(id); - var length = string.length; - var index = -1; - var codeUnit; - var result = ''; - var firstCodeUnit = string.charCodeAt(0); - while (++index < length) { - codeUnit = string.charCodeAt(index); - // Note: there’s no need to special-case astral symbols, surrogate - // pairs, or lone surrogates. - - // If the character is NULL (U+0000), then throw an - // `InvalidCharacterError` exception and terminate these steps. - if (codeUnit === 0x0000) { - throw new InvalidCharacterError( - 'Invalid character: the input contains U+0000.' - ); - } - - if ( - // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is - // U+007F, […] - (codeUnit >= 0x0001 && codeUnit <= 0x001F) || codeUnit == 0x007F || - // If the character is the first character and is in the range [0-9] - // (U+0030 to U+0039), […] - (index === 0 && codeUnit >= 0x0030 && codeUnit <= 0x0039) || - // If the character is the second character and is in the range [0-9] - // (U+0030 to U+0039) and the first character is a `-` (U+002D), […] - ( - index === 1 && - codeUnit >= 0x0030 && codeUnit <= 0x0039 && - firstCodeUnit === 0x002D - ) - ) { - // http://dev.w3.org/csswg/cssom/#escape-a-character-as-code-point - result += '\\' + codeUnit.toString(16) + ' '; - continue; - } - - // If the character is not handled by one of the above rules and is - // greater than or equal to U+0080, is `-` (U+002D) or `_` (U+005F), or - // is in one of the ranges [0-9] (U+0030 to U+0039), [A-Z] (U+0041 to - // U+005A), or [a-z] (U+0061 to U+007A), […] - if ( - codeUnit >= 0x0080 || - codeUnit === 0x002D || - codeUnit === 0x005F || - codeUnit >= 0x0030 && codeUnit <= 0x0039 || - codeUnit >= 0x0041 && codeUnit <= 0x005A || - codeUnit >= 0x0061 && codeUnit <= 0x007A - ) { - // the character itself - result += string.charAt(index); - continue; - } - - // Otherwise, the escaped character. - // http://dev.w3.org/csswg/cssom/#escape-a-character - result += '\\' + string.charAt(index); - - } - - return '#' + result; - -}; - /** * Calculate the easing pattern * @private @@ -309,16 +229,6 @@ smoothScroll.animateScroll = function (anchor, toggle, options) { * @private */ var hashChangeHandler = function (event) { - - // Get hash from URL - // var hash = decodeURIComponent( escapeCharacters( root.location.hash ) ); - var hash; - try { - hash = escapeCharacters(decodeURIComponent(root.location.hash)); - } catch (e) { - hash = escapeCharacters(root.location.hash); - } - // Only run if there's an anchor element to scroll to if (!anchor) return; @@ -331,7 +241,6 @@ var hashChangeHandler = function (event) { // Reset anchor and toggle anchor = null; toggle = null; - }; /** From 89ce8888195c175ebcac3674beb62e6b3173d33a Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Sat, 29 Apr 2017 03:15:54 +0200 Subject: [PATCH 4/7] Fixes. --- src/js/smooth-scroll.js | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/js/smooth-scroll.js b/src/js/smooth-scroll.js index 62bfe38..b173f32 100755 --- a/src/js/smooth-scroll.js +++ b/src/js/smooth-scroll.js @@ -1,5 +1,5 @@ +const root = window; var smoothScroll = {}; // Object for public APIs -var supports = 'querySelector' in document && 'addEventListener' in root; // Feature test var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; // Default settings @@ -260,13 +260,11 @@ var clickHandler = function (event) { if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; // Get the sanitized hash - // var hash = decodeURIComponent( escapeCharacters( toggle.hash ) ); - // console.log(hash); var hash; try { - hash = escapeCharacters(decodeURIComponent(toggle.hash)); + hash = decodeURIComponent(toggle.hash); } catch (e) { - hash = escapeCharacters(toggle.hash); + hash = toggle.hash; } // If the hash is empty, scroll to the top of the page @@ -356,9 +354,6 @@ smoothScroll.destroy = function () { */ smoothScroll.init = function (options) { - // feature test - if (!supports) return; - // Destroy any existing initializations smoothScroll.destroy(); @@ -380,10 +375,3 @@ smoothScroll.init = function (options) { } }; - - -// -// Public APIs -// - -export default smoothScroll; \ No newline at end of file From 77592e34e168c782dec71b829e69a017d58e0718 Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Sat, 29 Apr 2017 04:07:36 +0200 Subject: [PATCH 5/7] Use requestAnimationFrame, remove most of the easing functions, move smoothScroll to a class. --- index.html | 146 ++++++----------- src/js/smooth-scroll.js | 341 ++++++++++++++-------------------------- 2 files changed, 173 insertions(+), 314 deletions(-) diff --git a/index.html b/index.html index 11128dd..7c0a4b5 100644 --- a/index.html +++ b/index.html @@ -1,99 +1,55 @@ - - - Smooth Scroll - - - - - - - - -
- - - -
-

- Linear
- Linear (no other options)
-

- -

- Ease-In
- Quad
- Cubic
- Quart
- Quint -

- -

- Ease-In-Out
- Quad
- Cubic
- Quart
- Quint -

- -

- Ease-Out
- Quad
- Cubic
- Quart
- Quint -

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

- Non-ASCII Characters
- 中文 -

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

中文

- -

Bazinga!

- -

- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
.
- .
.
.
.
.
.
.
.
.
.
.
.
. -

- -

Back to the top

-
-
- - - - - - - + + + Smooth Scroll + + + + +
+ + +
+ Link + +

+ .
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
.
. +
.
.
.
.
.
.
.
.
.
.
.
. +

+ +

Destination

+ +
+
+ + + + + + \ No newline at end of file diff --git a/src/js/smooth-scroll.js b/src/js/smooth-scroll.js index b173f32..48ac885 100755 --- a/src/js/smooth-scroll.js +++ b/src/js/smooth-scroll.js @@ -1,13 +1,12 @@ const root = window; -var smoothScroll = {}; // Object for public APIs -var settings, anchor, toggle, fixedHeader, headerHeight, eventTimeout, animationInterval; +var settings, anchor, fixedHeader, headerHeight, eventTimeout, animationInterval; // Default settings var defaults = { selector: '[data-scroll]', selectorHeader: null, speed: 500, - easing: 'easeInOutCubic', + easing: 'easeOutCubic', offset: 0, callback: function () { } }; @@ -36,18 +35,8 @@ var getHeight = function (elem) { */ var easingPattern = function (type, time) { var pattern; - if (type === 'easeInQuad') pattern = time * time; // accelerating from zero velocity - if (type === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity - if (type === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity - 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 - if (type === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity - if (type === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration - if (type === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity - if (type === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity - 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 return pattern || time; // no easing, no acceleration }; @@ -100,7 +89,7 @@ var getDocumentHeight = function () { * @returns {Object} */ var getDataOptions = function (options) { - return !options || !(typeof JSON === 'object' && typeof JSON.parse === 'function') ? {} : JSON.parse(options); + return !options || JSON.parse(options); }; /** @@ -133,180 +122,21 @@ var adjustFocus = function (anchor, endLocation, isNum) { }; -/** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Element} toggle The element that toggled the scroll event - * @param {Object} options - */ -smoothScroll.animateScroll = function (anchor, toggle, options) { - - // Options and overrides - var overrides = getDataOptions(toggle ? toggle.getAttribute('data-options') : null); - var animateSettings = {}; - Object.assign(animateSettings, settings || defaults, options || {}, overrides); - - // Selectors and variables - var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if (!isNum && !anchorElem) return; - var startLocation = root.pageYOffset; // Current location on the page - if (animateSettings.selectorHeader && !fixedHeader) { - // Get the fixed header if not already set - fixedHeader = document.querySelector(animateSettings.selectorHeader); - } - if (!headerHeight) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight(fixedHeader); - } - var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - - /** - * Stop the scroll animation when it reaches its target (or the bottom/top of page) - * @private - * @param {Number} position Current position on the page - * @param {Number} endLocation Scroll to location - * @param {Number} animationInterval How much to scroll on this loop - */ - var stopAnimateScroll = function (position, endLocation, animationInterval) { - var currentLocation = root.pageYOffset; - if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - - // Clear the animation timer - clearInterval(animationInterval); - - // Bring the anchored element into focus - adjustFocus(anchor, endLocation, isNum); - - // Run callback after animation complete - animateSettings.callback(anchor, toggle); - - } - }; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function () { - timeLapsed += 16; - percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); - percentage = (percentage > 1) ? 1 : percentage; - position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); - root.scrollTo(0, Math.floor(position)); - stopAnimateScroll(position, endLocation, animationInterval); - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - clearInterval(animationInterval); - animationInterval = setInterval(loopAnimateScroll, 16); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if (root.pageYOffset === 0) { - root.scrollTo(0, 0); - } - - // Start scrolling animation - startAnimateScroll(); - -}; - /** * Handle has change event * @private */ var hashChangeHandler = function (event) { + anchor = document.getElementById(location.hash.substring(1)); + // Only run if there's an anchor element to scroll to if (!anchor) return; - // Reset the anchor element's ID - anchor.id = anchor.getAttribute('data-scroll-id'); - // Scroll to the anchored content - smoothScroll.animateScroll(anchor, toggle); + this.animateScroll(anchor); - // Reset anchor and toggle + // Reset anchor anchor = null; - toggle = null; -}; - -/** - * If smooth scroll element clicked, animate scroll - * @private - */ -var clickHandler = function (event) { - - // Don't run if right-click or command/control + click - if (event.button !== 0 || event.metaKey || event.ctrlKey) return; - - // Check if a smooth scroll link was clicked - toggle = event.target.closest(settings.selector); - if (!toggle || toggle.tagName.toLowerCase() !== 'a') return; - - // Only run if link is an anchor and points to the current page - if (toggle.hostname !== root.location.hostname || toggle.pathname !== root.location.pathname || !/#/.test(toggle.href)) return; - - // Get the sanitized hash - var hash; - try { - hash = decodeURIComponent(toggle.hash); - } catch (e) { - hash = toggle.hash; - } - - // If the hash is empty, scroll to the top of the page - if (hash === '#') { - - // Prevent default link behavior - event.preventDefault(); - - // Set the anchored element - anchor = document.body; - - // Save or create the ID as a data attribute and remove it (prevents scroll jump) - var id = anchor.id ? anchor.id : 'smooth-scroll-top'; - anchor.setAttribute('data-scroll-id', id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - // Otherwise, update the hash - if (root.location.hash.substring(1) === id) { - hashChangeHandler(); - } else { - root.location.hash = id; - } - - return; - - } - - // Get the anchored element - anchor = document.querySelector(hash); - - // If anchored element exists, save the ID as a data attribute and remove it (prevents scroll jump) - if (!anchor) return; - anchor.setAttribute('data-scroll-id', anchor.id); - anchor.id = ''; - - // If no hash change event will happen, fire manually - if (toggle.hash === root.location.hash) { - event.preventDefault(); - hashChangeHandler(); - } - }; /** @@ -324,54 +154,127 @@ var resizeThrottler = function (event) { } }; -/** - * Destroy the current initialization. - * @public - */ -smoothScroll.destroy = function () { - - // If plugin isn't already initialized, stop - if (!settings) return; +class SmoothScroll { - // Remove event listeners - document.removeEventListener('click', clickHandler, false); - root.removeEventListener('resize', resizeThrottler, false); - - // Reset varaibles - settings = null; - anchor = null; - toggle = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; -}; + /** + * Initialize Smooth Scroll + * @public + * @param {Object} options User settings + */ + constructor(options) { + // Selectors and variables + settings = {}; + Object.assign(settings, defaults, options || {}); + fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header + headerHeight = getHeaderHeight(fixedHeader); -/** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ -smoothScroll.init = function (options) { + // Listen for hash changes + root.addEventListener('hashchange', hashChangeHandler.bind(this), false); - // Destroy any existing initializations - smoothScroll.destroy(); + // If window is resized and there's a fixed header, recalculate its size + if (fixedHeader) { + root.addEventListener('resize', resizeThrottler, false); + } + } - // Selectors and variables - settings = {}; - Object.assign(settings, defaults, options || {}); - fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header - headerHeight = getHeaderHeight(fixedHeader); + /** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} anchor The element or position to scroll to + * @param {Object} options + */ + animateScroll(anchor, options) { + // Options + var animateSettings = {}; + Object.assign(animateSettings, settings || defaults, options || {}); + + // Selectors and variables + var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; + var anchorElem = isNum || !anchor.tagName ? null : anchor; + if (!isNum && !anchorElem) return; + var startLocation = root.pageYOffset; // Current location on the page + if (animateSettings.selectorHeader && !fixedHeader) { + // Get the fixed header if not already set + fixedHeader = document.querySelector(animateSettings.selectorHeader); + } + if (!headerHeight) { + // Get the height of a fixed header if one exists and not already set + headerHeight = getHeaderHeight(fixedHeader); + } + var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to + var distance = endLocation - startLocation; // distance to travel + var documentHeight = getDocumentHeight(); + var timeLapsed = 0; + var percentage, position; + var start = null; + + /** + * Loop scrolling animation + * @private + */ + var loopAnimateScroll = function(timestamp) { + if (!start) start = timestamp; + var progress = timestamp - start; + timeLapsed += progress; + percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); + percentage = (percentage > 1) ? 1 : percentage; + position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + root.scrollTo(0, Math.floor(position)); + console.log(percentage); + + var currentLocation = root.pageYOffset; + if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { + // Bring the anchored element into focus + adjustFocus(anchor, endLocation, isNum); + + // Run callback after animation complete + animateSettings.callback(anchor); + } else { + animationInterval = requestAnimationFrame(loopAnimateScroll); + } + }; + + /** + * Set interval timer + * @private + */ + var startAnimateScroll = function () { + start = null; + cancelAnimationFrame(animationInterval); + animationInterval = requestAnimationFrame(loopAnimateScroll); + }; + + /** + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 + */ + if (root.pageYOffset === 0) { + root.scrollTo(0, 0); + } - // When a toggle is clicked, run the click handler - document.addEventListener('click', clickHandler, false); + // Start scrolling animation + startAnimateScroll(); - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler, false); + } - // If window is resized and there's a fixed header, recalculate its size - if (fixedHeader) { - root.addEventListener('resize', resizeThrottler, false); + /** + * Destroy the current initialization. + * @public + */ + destroy() { + // If plugin isn't already initialized, stop + if (!settings) return; + + // Remove event listeners + root.removeEventListener('resize', resizeThrottler, false); + + // Reset varaibles + settings = null; + anchor = null; + fixedHeader = null; + headerHeight = null; + eventTimeout = null; + animationInterval = null; } -}; +} \ No newline at end of file From 221ac9491663408e51739543c76f3c25f3e53177 Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Sat, 29 Apr 2017 04:12:53 +0200 Subject: [PATCH 6/7] Updated Readme --- README.md | 270 ++---------------------------------------------------- 1 file changed, 9 insertions(+), 261 deletions(-) diff --git a/README.md b/README.md index 73cdd4d..511f198 100755 --- a/README.md +++ b/README.md @@ -1,269 +1,17 @@ -# Smooth Scroll [![Build Status](https://travis-ci.org/cferdinandi/smooth-scroll.svg)](https://travis-ci.org/cferdinandi/smooth-scroll) -A lightweight script to animate scrolling to anchor links. Smooth Scroll works great with [Gumshoe](https://github.com/cferdinandi/gumshoe). - -[Download Smooth Scroll](https://github.com/cferdinandi/smooth-scroll/archive/master.zip) / [View the demo](http://cferdinandi.github.io/smooth-scroll/) - - -
- -### Want to learn how to write your own vanilla JS plugins? Check out ["The Vanilla JS Guidebook"](https://gomakethings.com/vanilla-js-guidebook/) and level-up as a web developer. 🚀 - -
- - - -## Getting Started - -Compiled and production-ready code can be found in the `dist` directory. The `src` directory contains development code. - -### 1. Include Smooth Scroll on your site. - -```html - -``` - -### 2. Add the markup to your HTML. - -Turn anchor links into Smooth Scroll links by adding the `[data-scroll]` data attribute. Give the anchor location an ID just like you normally would. - -```html -Anchor Link -... -Bazinga! -``` - -### 3. Initialize Smooth Scroll. - -In the footer of your page, after the content, initialize Smooth Scroll. And that's it, you're done. Nice work! - -```html - -``` - - - -## Installing with Package Managers - -You can install Smooth Scroll with your favorite package manager. - -* **[NPM](https://www.npmjs.org/):** `npm install cferdinandi/smooth-scroll` -* **[Bower](http://bower.io/):** `bower install https://github.com/cferdinandi/smooth-scroll.git` -* **[Component](http://component.io/):** `component install cferdinandi/smooth-scroll` - - - -## Working with the Source Files - -If you would prefer, you can work with the development code in the `src` directory using the included [Gulp build system](http://gulpjs.com/). This compiles, lints, and minifies code. - -### Dependencies -Make sure these are installed first. - -* [Node.js](http://nodejs.org) -* [Gulp](http://gulpjs.com) `sudo npm install -g gulp` - -### Quick Start - -1. In bash/terminal/command line, `cd` into your project directory. -2. Run `npm install` to install required files. -3. When it's done installing, run one of the task runners to get going: - * `gulp` manually compiles files. - * `gulp watch` automatically compiles files when changes are made and applies changes using [LiveReload](http://livereload.com/). - - - -## Options and Settings - -Smooth Scroll includes smart defaults and works right out of the box. But if you want to customize things, it also has a robust API that provides multiple ways for you to adjust the default options and settings. - -### Global Settings - -You can pass options and callbacks into Smooth Scroll through the `init()` function: - -```javascript -smoothScroll.init({ - selector: '[data-scroll]', // Selector for links (must be a class, ID, data attribute, or element tag) - selectorHeader: null, // Selector for fixed headers (must be a valid CSS selector) [optional] - speed: 500, // Integer. How fast to complete the scroll in milliseconds - easing: 'easeInOutCubic', // Easing pattern to use - offset: 0, // Integer or Function returning an integer. How far to offset the scrolling anchor location in pixels - callback: function ( anchor, toggle ) {} // Function to run after scrolling -}); -``` - -***Note:*** *To programatically add Smooth Scroll to all anchor links on a page, pass `selector: 'a[href^="#"]'` into `init`.* - -#### Easing Options - -**Linear** -*Moves at the same speed from start to finish.* - -* `Linear` - - -**Ease-In** -*Gradually increases in speed.* - -* `easeInQuad` -* `easeInCubic` -* `easeInQuart` -* `easeInQuint` - - -**Ease-In-Out** -*Gradually increases in speed, peaks, and then gradually slows down.* - -* `easeInOutQuad` -* `easeInOutCubic` -* `easeInOutQuart` -* `easeInOutQuint` - - -**Ease-Out** -*Gradually decreases in speed.* - -* `easeOutQuad` -* `easeOutCubic` -* `easeOutQuart` -* `easeOutQuint` - - -Learn more about the different easing patterns and what they do at [easings.net](http://easings.net/). - -### Override settings with data attributes - -Smooth Scroll also lets you override global settings on a link-by-link basis using the `[data-options]` data attribute. - -```html - - Anchor Link - -``` - -***Note:*** *You must use [valid JSON](http://jsonlint.com/) in order for the `data-options` feature to work. Does not support the `callback` method.* - -### Use Smooth Scroll events in your own scripts - -You can also call Smooth Scroll's scroll animation events in your own scripts. - -#### animateScroll() -Animate scrolling to an anchor. - -```javascript -smoothScroll.animateScroll( - anchor, // Node to scroll to. ex. document.querySelector( '#bazinga' ) - toggle, // Node that toggles the animation, OR an integer. ex. document.querySelector( '#toggle' ) - options // Classes and callbacks. Same options as those passed into the init() function. -); -``` - -**Example 1** - -```javascript -var anchor = document.querySelector( '#bazinga' ); -smoothScroll.animateScroll( anchor ); -``` - -**Example 2** - -```javascript -var anchor = document.querySelector( '#bazinga' ); -var toggle = document.querySelector('#toggle'); -var options = { speed: 1000, easing: 'easeOutCubic' }; -smoothScroll.animateScroll( anchor, toggle, options ); -``` - -**Example 3** - -```javascript -// You can optionally pass in a y-position to scroll to as an integer -smoothScroll.animateScroll( 750 ); -``` - -#### destroy() -Destroy the current `smoothScroll.init()`. This is called automatically during the `init` function to remove any existing initializations. +# Smooth Scroll - Work In Progress +A simplified, modern version of the [original smooth scroll](https://github.com/cferdinandi/smooth-scroll). ```javascript -smoothScroll.destroy(); -``` - - -### Fixed Headers - -If you're using a fixed header, Smooth Scroll will automatically offset scroll distances by the header height. Pass in a valid CSS selector for your fixed header as an option to the `init`. + const a = document.getElementById('link'); + const destination = document.getElementById('destination'); + const smooth = new SmoothScroll(); -If you have multiple fixed headers, pass in the last one in the markup. - -```html - -... - + a.addEventListener('click', e => { + smooth.animateScroll(destination, {speed: 5000}); + e.preventDefault(); + }); ``` -### Animating links to other pages - -This is an often requested feature, but Smooth Scroll does not include an option to animate scrolling to links on other pages. - -You can attempt to implement it using the API, but it's very difficult to prevent the automatic browser jump when the page loads, and anything I've done to work around it results in weird, janky issues, so I've decided to leave this out of the core. Here's a potential workaround... - -1. Do *not* add the `data-scroll` attribute to links to other pages. Treat them like normal links, and include your anchor link hash as normal. - - ```html - - ``` -2. Add the following script to the footer of your page, after the `smoothScroll.init()` function. - - ```html - - ``` - - -## Browser Compatibility - -Smooth Scroll works in all modern browsers, and IE 9 and above. - -Smooth Scroll is built with modern JavaScript APIs, and uses progressive enhancement. If the JavaScript file fails to load, or if your site is viewed on older and less capable browsers, anchor links will jump the way they normally would. - - -## Known Issues - -### `` styling - -If the `` element has been assigned a height of `100%` or `overflow: hidden`, Smooth Scroll is unable to properly calculate page distances and will not scroll to the right location. The `` element can have a fixed, non-percentage based height (ex. `500px`), or a height of `auto`, and an `overflow` of `visible`. - -### Animating from the bottom - -Animated scrolling links at the very bottom of the page (example: a "scroll to top" link) will stop animated almost immediately after they start when using certain easing patterns. This is an issue that's been around for a while and I've yet to find a good fix for it. I've found that `easeOut*` easing patterns work as expected, but other patterns can cause issues. [See this discussion for more details.](https://github.com/cferdinandi/smooth-scroll/issues/49) - - - -## How to Contribute - -Please review the [contributing guidelines](CONTRIBUTING.md). - - - ## License The code is available under the [MIT License](LICENSE.md). \ No newline at end of file From 4981f43db47935ec70699c4070e5bb2c37b18848 Mon Sep 17 00:00:00 2001 From: Konrad Dzwinel Date: Tue, 2 May 2017 12:14:30 +0200 Subject: [PATCH 7/7] ES6 module, move demo, clean up Readme, fix hash update. --- .gitignore | 6 +- README.md | 25 ++- index.html => demo/index.html | 14 +- demo/main.js | 9 ++ demo/package.json | 11 ++ demo/webpack.config.js | 10 ++ org.min.js | 2 + package.json | 2 +- src/helpers.js | 69 +++++++++ src/js/smooth-scroll.js | 280 ---------------------------------- src/smooth-scroll.js | 82 ++++++++++ 11 files changed, 206 insertions(+), 304 deletions(-) rename index.html => demo/index.html (78%) create mode 100644 demo/main.js create mode 100644 demo/package.json create mode 100644 demo/webpack.config.js create mode 100644 org.min.js create mode 100644 src/helpers.js delete mode 100755 src/js/smooth-scroll.js create mode 100755 src/smooth-scroll.js diff --git a/.gitignore b/.gitignore index 62fb128..2baca95 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,5 @@ -# Node -node_modules -test/results -test/coverage +demo/node_modules +demo/*.min.js ## OS X .DS_Store diff --git a/README.md b/README.md index 511f198..9a1ef45 100755 --- a/README.md +++ b/README.md @@ -2,16 +2,27 @@ A simplified, modern version of the [original smooth scroll](https://github.com/cferdinandi/smooth-scroll). ```javascript - const a = document.getElementById('link'); - const destination = document.getElementById('destination'); - const smooth = new SmoothScroll(); +import animateScroll from './path/smooth-scroll.js'; - a.addEventListener('click', e => { - smooth.animateScroll(destination, {speed: 5000}); - e.preventDefault(); - }); +const a = document.getElementById('link'); +const destination = document.getElementById('destination'); + +a.addEventListener('click', e => { + animateScroll(destination, {speed: 5000}); + e.preventDefault(); +}); ``` +This version, compared to the original, is: + +- it's 50% smaller +- it's an ES6 module +- it uses `requestAnimationFrame` instead of `setInterval` +- it doesn't include polyfills (closest, Object.assign / extend). If you really need them, include them yourself. +- it doesn't escape characters from hash (no [CSS.escape](https://github.com/mathiasbynens/CSS.escape)) +- includes only two easing options (`easeOutCubic`, `easeInCubic`) instead of 12. If you need a different one, pass a function as an `easing` param. +- it doesn't track or measure your header. If you need it, measure it yourself and pass to the SmoothScroll via the `offset` param (you can also pass a function here). + ## License The code is available under the [MIT License](LICENSE.md). \ No newline at end of file diff --git a/index.html b/demo/index.html similarity index 78% rename from index.html rename to demo/index.html index 7c0a4b5..5dd7614 100644 --- a/index.html +++ b/demo/index.html @@ -38,18 +38,8 @@

Smooth Scroll

- - - + + \ No newline at end of file diff --git a/demo/main.js b/demo/main.js new file mode 100644 index 0000000..d95b76f --- /dev/null +++ b/demo/main.js @@ -0,0 +1,9 @@ +import animateScroll from '../src/smooth-scroll.js'; + +const a = document.getElementById('link'); +const destination = document.getElementById('destination'); + +a.addEventListener('click', e => { + animateScroll(destination, {speed: 5000}); + e.preventDefault(); +}); \ No newline at end of file diff --git a/demo/package.json b/demo/package.json new file mode 100644 index 0000000..f91db1e --- /dev/null +++ b/demo/package.json @@ -0,0 +1,11 @@ +{ + "name": "demo", + "version": "1.0.0", + "description": "", + "main": "main.js", + "scripts": { + "build": "webpack ." + }, + "author": "Konrad Dzwinel ", + "license": "ISC" +} diff --git a/demo/webpack.config.js b/demo/webpack.config.js new file mode 100644 index 0000000..1b1a323 --- /dev/null +++ b/demo/webpack.config.js @@ -0,0 +1,10 @@ +const BabiliPlugin = require("babili-webpack-plugin"); +module.exports = { + entry: './main.js', + output: { + filename: 'main.min.js' + }, + plugins: [ + new BabiliPlugin() + ] +} \ No newline at end of file diff --git a/org.min.js b/org.min.js new file mode 100644 index 0000000..184687a --- /dev/null +++ b/org.min.js @@ -0,0 +1,2 @@ +/*! smooth-scroll v11.0.1 | (c) 2017 Chris Ferdinandi | GPL-3.0 License | http://github.com/cferdinandi/smooth-scroll */ +!(function(e,t){"function"==typeof define&&define.amd?define([],t(e)):"object"==typeof exports?module.exports=t(e):e.smoothScroll=t(e)})("undefined"!=typeof global?global:this.window||this.global,(function(e){"use strict";var t,n,o,r,a,c,i,l={},u="querySelector"in document&&"addEventListener"in e,s={selector:"[data-scroll]",selectorHeader:null,speed:500,offset:0,easing:"easeInOutCubic",easingPatterns:{},before:function(){},after:function(){}},f=function(){var e={},t=!1,n=0,o=arguments.length;"[object Boolean]"===Object.prototype.toString.call(arguments[0])&&(t=arguments[0],n++);for(;n=0&&t.item(n)!==this;);return n>-1});e&&e!==document;e=e.parentNode)if(e.matches(t))return e;return null},m=function(e){"#"===e.charAt(0)&&(e=e.substr(1));for(var t,n=String(e),o=n.length,r=-1,a="",c=n.charCodeAt(0);++r=1&&t<=31||127==t||0===r&&t>=48&&t<=57||1===r&&t>=48&&t<=57&&45===c?a+="\\"+t.toString(16)+" ":a+=t>=128||45===t||95===t||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122?n.charAt(r):"\\"+n.charAt(r)}return"#"+a},p=function(e,n){var o;return"easeInQuad"===e&&(o=n*n),"easeOutQuad"===e&&(o=n*(2-n)),"easeInOutQuad"===e&&(o=n<.5?2*n*n:(4-2*n)*n-1),"easeInCubic"===e&&(o=n*n*n),"easeOutCubic"===e&&(o=--n*n*n+1),"easeInOutCubic"===e&&(o=n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1),"easeInQuart"===e&&(o=n*n*n*n),"easeOutQuart"===e&&(o=1- --n*n*n*n),"easeInOutQuart"===e&&(o=n<.5?8*n*n*n*n:1-8*--n*n*n*n),"easeInQuint"===e&&(o=n*n*n*n*n),"easeOutQuint"===e&&(o=1+--n*n*n*n*n),"easeInOutQuint"===e&&(o=n<.5?16*n*n*n*n*n:1+16*--n*n*n*n*n),t.easingPatterns[e]&&(o=t.easingPatterns[e](n)),o||n},g=function(e,t,n){var o=0;if(e.offsetParent)do{o+=e.offsetTop,e=e.offsetParent}while(e);return o=Math.max(o-t-n,0),Math.min(o,y()-b())},b=function(){return Math.max(document.documentElement.clientHeight,e.innerHeight||0)},y=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)},v=function(e){return e&&"object"==typeof JSON&&"function"==typeof JSON.parse?JSON.parse(e):{}},O=function(e){return e?d(e)+e.offsetTop:0},S=function(t,n,o){o||(t.focus(),document.activeElement.id!==t.id&&(t.setAttribute("tabindex","-1"),t.focus(),t.style.outline="none"),e.scrollTo(0,n))};l.animateScroll=function(n,o,c){var l=v(o?o.getAttribute("data-options"):null),u=f(t||s,c||{},l),d="[object Number]"===Object.prototype.toString.call(n),h=d||!n.tagName?null:n;if(d||h){var m=e.pageYOffset;u.selectorHeader&&!r&&(r=document.querySelector(u.selectorHeader)),a||(a=O(r));var b,E,I=d?n:g(h,a,parseInt("function"==typeof u.offset?u.offset():u.offset,10)),H=I-m,A=y(),j=0,C=function(t,r,a){var c=e.pageYOffset;(t==r||c==r||e.innerHeight+c>=A)&&(clearInterval(a),S(n,r,d),u.after(n,o))},M=function(){j+=16,b=j/parseInt(u.speed,10),b=b>1?1:b,E=m+H*p(u.easing,b),e.scrollTo(0,Math.floor(E)),C(E,I,i)};0===e.pageYOffset&&e.scrollTo(0,0),u.before(n,o),(function(){clearInterval(i),i=setInterval(M,16)})()}};var E=function(t){try{m(decodeURIComponent(e.location.hash))}catch(t){m(e.location.hash)}n&&(n.id=n.getAttribute("data-scroll-id"),l.animateScroll(n,o),n=null,o=null)},I=function(r){if(0===r.button&&!r.metaKey&&!r.ctrlKey&&(o=h(r.target,t.selector))&&"a"===o.tagName.toLowerCase()&&o.hostname===e.location.hostname&&o.pathname===e.location.pathname&&/#/.test(o.href)){var a;try{a=m(decodeURIComponent(o.hash))}catch(e){a=m(o.hash)}if("#"===a){r.preventDefault(),n=document.body;var c=n.id?n.id:"smooth-scroll-top";return n.setAttribute("data-scroll-id",c),n.id="",void(e.location.hash.substring(1)===c?E():e.location.hash=c)}n=document.querySelector(a),n&&(n.setAttribute("data-scroll-id",n.id),n.id="",o.hash===e.location.hash&&(r.preventDefault(),E()))}},H=function(e){c||(c=setTimeout((function(){c=null,a=O(r)}),66))};return l.destroy=function(){t&&(document.removeEventListener("click",I,!1),e.removeEventListener("resize",H,!1),t=null,n=null,o=null,r=null,a=null,c=null,i=null)},l.init=function(n){u&&(l.destroy(),t=f(s,n||{}),r=t.selectorHeader?document.querySelector(t.selectorHeader):null,a=O(r),document.addEventListener("click",I,!1),e.addEventListener("hashchange",E,!1),r&&e.addEventListener("resize",H,!1))},l})); \ No newline at end of file diff --git a/package.json b/package.json index 3de48af..64d8230 100755 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "smooth-scroll", "version": "10.3.1", "description": "Animate scrolling to anchor links", - "main": "./dist/js/smooth-scroll.min.js", + "main": "./src/smooth-scroll.js", "author": { "name": "Chris Ferdinandi", "url": "http://gomakethings.com/" diff --git a/src/helpers.js b/src/helpers.js new file mode 100644 index 0000000..63cc67b --- /dev/null +++ b/src/helpers.js @@ -0,0 +1,69 @@ +/** + * Calculate the easing pattern + * @private + * @link https://gist.github.com/gre/1650294 + * @param {String} easing Easing pattern + * @param {Number} time Time animation should take to complete + * @returns {Number} + */ +export const easingPattern = function (easing, time) { + let pattern; + if (easing === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity + if (easing === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity + if (typeof easing === 'function') pattern = easing(time); + return pattern || time; // no easing, no acceleration +}; + +/** + * Calculate how far to scroll + * @private + * @param {Element} anchor The anchor element to scroll to + * @param {Number} offset Number of pixels by which to offset scroll + * @returns {Number} + */ +export const getEndLocation = function (anchor, offset) { + let location = 0; + if (anchor.offsetParent) { + do { + location += anchor.offsetTop; + anchor = anchor.offsetParent; + } while (anchor); + } + location = Math.max(location - offset, 0); + return Math.min(location, getDocumentHeight() - getViewportHeight()); +}; + +/** + * Determine the viewport's height + * @private + * @returns {Number} + */ +export const getViewportHeight = () => Math.max(document.documentElement.clientHeight, window.innerHeight || 0); + +/** + * Determine the document's height + * @private + * @returns {Number} + */ +export const getDocumentHeight = () => { + return Math.max( + document.body.scrollHeight, document.documentElement.scrollHeight, + document.body.offsetHeight, document.documentElement.offsetHeight, + document.body.clientHeight, document.documentElement.clientHeight + ); +}; + +/** + * Bring the anchored element into focus + * @private + */ +export const adjustFocus = function (anchor, endLocation) { + // Otherwise, bring anchor element into focus + anchor.focus(); + if (document.activeElement.id !== anchor.id) { + anchor.setAttribute('tabindex', '-1'); + anchor.focus(); + anchor.style.outline = 'none'; + } + window.scrollTo(0, endLocation); +}; \ No newline at end of file diff --git a/src/js/smooth-scroll.js b/src/js/smooth-scroll.js deleted file mode 100755 index 48ac885..0000000 --- a/src/js/smooth-scroll.js +++ /dev/null @@ -1,280 +0,0 @@ -const root = window; -var settings, anchor, fixedHeader, headerHeight, eventTimeout, animationInterval; - -// Default settings -var defaults = { - selector: '[data-scroll]', - selectorHeader: null, - speed: 500, - easing: 'easeOutCubic', - offset: 0, - callback: function () { } -}; - -// -// Methods -// - -/** - * Get the height of an element. - * @private - * @param {Node} elem The element to get the height of - * @return {Number} The element's height in pixels - */ -var getHeight = function (elem) { - return Math.max(elem.scrollHeight, elem.offsetHeight, elem.clientHeight); -}; - -/** - * Calculate the easing pattern - * @private - * @link https://gist.github.com/gre/1650294 - * @param {String} type Easing pattern - * @param {Number} time Time animation should take to complete - * @returns {Number} - */ -var easingPattern = function (type, time) { - var pattern; - if (type === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity - if (type === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity - return pattern || time; // no easing, no acceleration -}; - -/** - * Calculate how far to scroll - * @private - * @param {Element} anchor The anchor element to scroll to - * @param {Number} headerHeight Height of a fixed header, if any - * @param {Number} offset Number of pixels by which to offset scroll - * @returns {Number} - */ -var getEndLocation = function (anchor, headerHeight, offset) { - var location = 0; - if (anchor.offsetParent) { - do { - location += anchor.offsetTop; - anchor = anchor.offsetParent; - } while (anchor); - } - location = Math.max(location - headerHeight - offset, 0); - return Math.min(location, getDocumentHeight() - getViewportHeight()); -}; - -/** - * Determine the viewport's height - * @private - * @returns {Number} - */ -var getViewportHeight = function () { - return Math.max(document.documentElement.clientHeight, root.innerHeight || 0); -}; - -/** - * Determine the document's height - * @private - * @returns {Number} - */ -var getDocumentHeight = function () { - return Math.max( - document.body.scrollHeight, document.documentElement.scrollHeight, - document.body.offsetHeight, document.documentElement.offsetHeight, - document.body.clientHeight, document.documentElement.clientHeight - ); -}; - -/** - * Convert data-options attribute into an object of key/value pairs - * @private - * @param {String} options Link-specific options as a data attribute string - * @returns {Object} - */ -var getDataOptions = function (options) { - return !options || JSON.parse(options); -}; - -/** - * Get the height of the fixed header - * @private - * @param {Node} header The header - * @return {Number} The height of the header - */ -var getHeaderHeight = function (header) { - return !header ? 0 : (getHeight(header) + header.offsetTop); -}; - -/** - * Bring the anchored element into focus - * @private - */ -var adjustFocus = function (anchor, endLocation, isNum) { - - // Don't run if scrolling to a number on the page - if (isNum) return; - - // Otherwise, bring anchor element into focus - anchor.focus(); - if (document.activeElement.id !== anchor.id) { - anchor.setAttribute('tabindex', '-1'); - anchor.focus(); - anchor.style.outline = 'none'; - } - root.scrollTo(0, endLocation); - -}; - -/** - * Handle has change event - * @private - */ -var hashChangeHandler = function (event) { - anchor = document.getElementById(location.hash.substring(1)); - - // Only run if there's an anchor element to scroll to - if (!anchor) return; - - // Scroll to the anchored content - this.animateScroll(anchor); - - // Reset anchor - anchor = null; -}; - -/** - * On window scroll and resize, only run events at a rate of 15fps for better performance - * @private - * @param {Function} eventTimeout Timeout function - * @param {Object} settings - */ -var resizeThrottler = function (event) { - if (!eventTimeout) { - eventTimeout = setTimeout(function () { - eventTimeout = null; // Reset timeout - headerHeight = getHeaderHeight(fixedHeader); // Get the height of a fixed header if one exists - }, 66); - } -}; - -class SmoothScroll { - - /** - * Initialize Smooth Scroll - * @public - * @param {Object} options User settings - */ - constructor(options) { - // Selectors and variables - settings = {}; - Object.assign(settings, defaults, options || {}); - fixedHeader = settings.selectorHeader ? document.querySelector(settings.selectorHeader) : null; // Get the fixed header - headerHeight = getHeaderHeight(fixedHeader); - - // Listen for hash changes - root.addEventListener('hashchange', hashChangeHandler.bind(this), false); - - // If window is resized and there's a fixed header, recalculate its size - if (fixedHeader) { - root.addEventListener('resize', resizeThrottler, false); - } - } - - /** - * Start/stop the scrolling animation - * @public - * @param {Node|Number} anchor The element or position to scroll to - * @param {Object} options - */ - animateScroll(anchor, options) { - // Options - var animateSettings = {}; - Object.assign(animateSettings, settings || defaults, options || {}); - - // Selectors and variables - var isNum = Object.prototype.toString.call(anchor) === '[object Number]' ? true : false; - var anchorElem = isNum || !anchor.tagName ? null : anchor; - if (!isNum && !anchorElem) return; - var startLocation = root.pageYOffset; // Current location on the page - if (animateSettings.selectorHeader && !fixedHeader) { - // Get the fixed header if not already set - fixedHeader = document.querySelector(animateSettings.selectorHeader); - } - if (!headerHeight) { - // Get the height of a fixed header if one exists and not already set - headerHeight = getHeaderHeight(fixedHeader); - } - var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10)); // Location to scroll to - var distance = endLocation - startLocation; // distance to travel - var documentHeight = getDocumentHeight(); - var timeLapsed = 0; - var percentage, position; - var start = null; - - /** - * Loop scrolling animation - * @private - */ - var loopAnimateScroll = function(timestamp) { - if (!start) start = timestamp; - var progress = timestamp - start; - timeLapsed += progress; - percentage = (timeLapsed / parseInt(animateSettings.speed, 10)); - percentage = (percentage > 1) ? 1 : percentage; - position = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); - root.scrollTo(0, Math.floor(position)); - console.log(percentage); - - var currentLocation = root.pageYOffset; - if (position == endLocation || currentLocation == endLocation || ((root.innerHeight + currentLocation) >= documentHeight)) { - // Bring the anchored element into focus - adjustFocus(anchor, endLocation, isNum); - - // Run callback after animation complete - animateSettings.callback(anchor); - } else { - animationInterval = requestAnimationFrame(loopAnimateScroll); - } - }; - - /** - * Set interval timer - * @private - */ - var startAnimateScroll = function () { - start = null; - cancelAnimationFrame(animationInterval); - animationInterval = requestAnimationFrame(loopAnimateScroll); - }; - - /** - * Reset position to fix weird iOS bug - * @link https://github.com/cferdinandi/smooth-scroll/issues/45 - */ - if (root.pageYOffset === 0) { - root.scrollTo(0, 0); - } - - // Start scrolling animation - startAnimateScroll(); - - } - - /** - * Destroy the current initialization. - * @public - */ - destroy() { - // If plugin isn't already initialized, stop - if (!settings) return; - - // Remove event listeners - root.removeEventListener('resize', resizeThrottler, false); - - // Reset varaibles - settings = null; - anchor = null; - fixedHeader = null; - headerHeight = null; - eventTimeout = null; - animationInterval = null; - } - -} \ No newline at end of file diff --git a/src/smooth-scroll.js b/src/smooth-scroll.js new file mode 100755 index 0000000..1ee281e --- /dev/null +++ b/src/smooth-scroll.js @@ -0,0 +1,82 @@ +import { easingPattern, getEndLocation, getViewportHeight, getDocumentHeight, adjustFocus } from './helpers'; + +const defaults = { + speed: 500, + easing: 'easeOutCubic', + offset: 0, + callback: function () { } +}; + +/** + * Start/stop the scrolling animation + * @public + * @param {Node|Number} target The element or position to scroll to + * @param {Object} options + */ +function animateScroll(target, options) { + // Options + var animateSettings = {}; + Object.assign(animateSettings, defaults, options || {}); + + // Selectors and variables + const isNum = (typeof target === 'number'); + if (!isNum && !(target instanceof Element)) + return; + + const offset = parseInt((typeof animateSettings.offset === 'function' ? animateSettings.offset() : animateSettings.offset), 10); + const startLocation = window.pageYOffset; // Current location on the page + const endLocation = isNum ? target : getEndLocation(target, offset); // Location to scroll to + const distance = endLocation - startLocation; // distance to travel + const timeEnd = parseInt(animateSettings.speed, 10); + const documentHeight = getDocumentHeight(); + let timeLapsed = 0; + let percentage; + let position; + let timeStart; + let animationInterval; + + /** + * Loop scrolling animation + * @private + */ + const loopAnimateScroll = function (timestamp) { + if (!timeStart) { + timeStart = timestamp; + } + + const frameLength = timestamp - timeStart; + timeLapsed += frameLength; + const percentage = Math.min((timeLapsed / timeEnd), 1); + const newPosition = startLocation + (distance * easingPattern(animateSettings.easing, percentage)); + window.scrollTo(0, Math.floor(newPosition)); + + var currentLocation = window.pageYOffset; + if (newPosition === endLocation || currentLocation === endLocation || ((window.innerHeight + currentLocation) >= documentHeight)) { + // Bring the anchored element into focus + if (!isNum) { + adjustFocus(target, endLocation); + if (target.id) { + location.hash = target.id; + } + } + + // Run callback after animation complete + animateSettings.callback(target); + } else { + animationInterval = requestAnimationFrame(loopAnimateScroll); + } + }; + + /** + * Reset position to fix weird iOS bug + * @link https://github.com/cferdinandi/smooth-scroll/issues/45 + */ + if (window.pageYOffset === 0) { + window.scrollTo(0, 0); + } + + // Start scrolling animation + requestAnimationFrame(loopAnimateScroll) +} + +export default animateScroll; \ No newline at end of file