Replace jQuery Smooth Scroll with Smooth Scroll + Gumshoe (#2082)

* Replace jQuery Smooth Scroll with Smooth Scroll + Gumshoe
* Change smooth scrolling speed
* Set maximum smooth scroll duration
* Remove Font Awesome CSS Ppseudo elements attribute from JS script

Close #2050, close #2075
This commit is contained in:
Michael Rose 2019-03-22 16:01:28 -04:00 committed by GitHub
parent 94e8280950
commit a44dc2f914
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 1149 additions and 78 deletions

View file

@ -9,7 +9,7 @@
{% endfor %}
{% else %}
<script src="{{ '/assets/js/main.min.js' | relative_url }}"></script>
<script data-search-pseudo-elements defer src="https://use.fontawesome.com/releases/v5.7.1/js/all.js" integrity="sha384-eVEQC9zshBn0rFj4+TU78eNA19HMNigMviK/PU/FFjLXqa/GKPgX58rvt5Z8PLs7" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.7.1/js/all.js" integrity="sha384-eVEQC9zshBn0rFj4+TU78eNA19HMNigMviK/PU/FFjLXqa/GKPgX58rvt5Z8PLs7" crossorigin="anonymous"></script>
{% endif %}
{% if site.search == true or page.layout == "search" %}

View file

@ -5,13 +5,15 @@
$(document).ready(function() {
// Sticky footer
var bumpIt = function() {
$("body").css("margin-bottom", $(".page__footer").outerHeight(true));
};
$("body").css("margin-bottom", $(".page__footer").outerHeight(true));
};
bumpIt();
$(window).resize(jQuery.throttle(250, function() {
bumpIt();
}));
$(window).resize(
jQuery.throttle(250, function() {
bumpIt();
})
);
// FitVids init
$("#main").fitVids();
@ -64,65 +66,30 @@ $(document).ready(function() {
});
// Smooth scrolling
// Bind popstate event listener to support back/forward buttons.
var smoothScrolling = false;
$(window).bind("popstate", function (event) {
$.smoothScroll({
scrollTarget: decodeURI(location.hash),
offset: -20,
beforeScroll: function() { smoothScrolling = true; },
afterScroll: function() { smoothScrolling = false; }
});
var scroll = new SmoothScroll('a[href*="#"]', {
offset: 20,
speed: 400,
speedAsDuration: true,
durationMax: 500
});
// Override clicking on links to smooth scroll
$('a[href*="#"]').bind("click", function (event) {
if (this.pathname === location.pathname && this.hash) {
event.preventDefault();
history.pushState(null, null, this.hash);
$(window).trigger("popstate");
}
});
// Smooth scroll on page load if there is a hash in the URL.
if (location.hash) {
$(window).trigger("popstate");
}
// Scrollspy equivalent: update hash fragment while scrolling.
$(window).scroll(jQuery.throttle(250, function() {
// Don't run while smooth scrolling (from clicking on a link).
if (smoothScrolling) return;
var scrollTop = $(window).scrollTop() + 20 + 1; // 20 = offset
var links = [];
$("nav.toc a").each(function() {
var link = $(this);
var href = link.attr("href");
if (href && href[0] == "#") {
var element = $(href);
links.push({
link: link,
href: href,
top: element.offset().top
});
link.removeClass('active');
}
});
for (var i = 0; i < links.length; i++) {
var top = links[i].top;
var bottom = (i < links.length - 1 ? links[i+1].top : Infinity);
if (top <= scrollTop && scrollTop < bottom) {
// Mark all ancestors as active
links[i].link.parents("li").children("a").addClass('active');
if (links[i].href !== decodeURI(location.hash)) {
history.replaceState(null, null, links[i].href);
}
return;
}
}
if ('#' !== location.hash) {
history.replaceState(null, null, '#');
}
}));
// Gumshoe scroll spy init
var spy = new Gumshoe("nav.toc a", {
// Active classes
navClass: "active", // applied to the nav list item
contentClass: "active", // applied to the content
// Nested navigation
nested: false, // if true, add classes to parents of active link
nestedClass: "active", // applied to the parent items
// Offset & reflow
offset: 20, // how far from the top of the page to activate a content area
reflow: true, // if true, listen for reflows
// Event support
events: true // if true, emit custom events
});
// add lightbox class to all image links
$(

File diff suppressed because one or more lines are too long

482
assets/js/plugins/gumshoe.js vendored Normal file
View file

@ -0,0 +1,482 @@
/*!
* gumshoejs v5.1.0
* A simple, framework-agnostic scrollspy script.
* (c) 2019 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/gumshoe
*/
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([], (function () {
return factory(root);
}));
} else if ( typeof exports === 'object' ) {
module.exports = factory(root);
} else {
root.Gumshoe = factory(root);
}
})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
'use strict';
//
// Defaults
//
var defaults = {
// Active classes
navClass: 'active',
contentClass: 'active',
// Nested navigation
nested: false,
nestedClass: 'active',
// Offset & reflow
offset: 0,
reflow: false,
// Event support
events: true
};
//
// Methods
//
/**
* Merge two or more objects together.
* @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
var extend = function () {
var merged = {};
Array.prototype.forEach.call(arguments, (function (obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) return;
merged[key] = obj[key];
}
}));
return merged;
};
/**
* Emit a custom event
* @param {String} type The event type
* @param {Node} elem The element to attach the event to
* @param {Object} detail Any details to pass along with the event
*/
var emitEvent = function (type, elem, detail) {
// Make sure events are enabled
if (!detail.settings.events) return;
// Create a new event
var event = new CustomEvent(type, {
bubbles: true,
cancelable: true,
detail: detail
});
// Dispatch the event
elem.dispatchEvent(event);
};
/**
* Get an element's distance from the top of the Document.
* @param {Node} elem The element
* @return {Number} Distance from the top in pixels
*/
var getOffsetTop = function (elem) {
var location = 0;
if (elem.offsetParent) {
while (elem) {
location += elem.offsetTop;
elem = elem.offsetParent;
}
}
return location >= 0 ? location : 0;
};
/**
* Sort content from first to last in the DOM
* @param {Array} contents The content areas
*/
var sortContents = function (contents) {
contents.sort((function (item1, item2) {
var offset1 = getOffsetTop(item1.content);
var offset2 = getOffsetTop(item2.content);
if (offset1 < offset2) return -1;
return 1;
}));
};
/**
* Get the offset to use for calculating position
* @param {Object} settings The settings for this instantiation
* @return {Float} The number of pixels to offset the calculations
*/
var getOffset = function (settings) {
// if the offset is a function run it
if (typeof settings.offset === 'function') {
return parseFloat(settings.offset());
}
// Otherwise, return it as-is
return parseFloat(settings.offset);
};
/**
* Get the document element'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
);
};
/**
* Determine if an element is in view
* @param {Node} elem The element
* @param {Object} settings The settings for this instantiation
* @param {Boolean} bottom If true, check if element is above bottom of viewport instead
* @return {Boolean} Returns true if element is in the viewport
*/
var isInView = function (elem, settings, bottom) {
var bounds = elem.getBoundingClientRect();
var offset = getOffset(settings);
if (bottom) {
return parseInt(bounds.bottom, 10) < (window.innerHeight || document.documentElement.clientHeight);
}
return parseInt(bounds.top, 10) <= offset;
};
/**
* Check if at the bottom of the viewport
* @return {Boolean} If true, page is at the bottom of the viewport
*/
var isAtBottom = function () {
if (window.innerHeight + window.pageYOffset >= getDocumentHeight()) return true;
return false;
};
/**
* Check if the last item should be used (even if not at the top of the page)
* @param {Object} item The last item
* @param {Object} settings The settings for this instantiation
* @return {Boolean} If true, use the last item
*/
var useLastItem = function (item, settings) {
if (isAtBottom() && isInView(item.content, settings, true)) return true;
return false;
};
/**
* Get the active content
* @param {Array} contents The content areas
* @param {Object} settings The settings for this instantiation
* @return {Object} The content area and matching navigation link
*/
var getActive = function (contents, settings) {
var last = contents[contents.length-1];
if (useLastItem(last, settings)) return last;
for (var i = contents.length - 1; i >= 0; i--) {
if (isInView(contents[i].content, settings)) return contents[i];
}
};
/**
* Deactivate parent navs in a nested navigation
* @param {Node} nav The starting navigation element
* @param {Object} settings The settings for this instantiation
*/
var deactivateNested = function (nav, settings) {
// If nesting isn't activated, bail
if (!settings.nested) return;
// Get the parent navigation
var li = nav.parentNode.closest('li');
if (!li) return;
// Remove the active class
li.classList.remove(settings.nestedClass);
// Apply recursively to any parent navigation elements
deactivateNested(li, settings);
};
/**
* Deactivate a nav and content area
* @param {Object} items The nav item and content to deactivate
* @param {Object} settings The settings for this instantiation
*/
var deactivate = function (items, settings) {
// Make sure their are items to deactivate
if (!items) return;
// Get the parent list item
var li = items.nav.closest('li');
if (!li) return;
// Remove the active class from the nav and content
li.classList.remove(settings.navClass);
items.content.classList.remove(settings.contentClass);
// Deactivate any parent navs in a nested navigation
deactivateNested(li, settings);
// Emit a custom event
emitEvent('gumshoeDeactivate', li, {
link: items.nav,
content: items.content,
settings: settings
});
};
/**
* Activate parent navs in a nested navigation
* @param {Node} nav The starting navigation element
* @param {Object} settings The settings for this instantiation
*/
var activateNested = function (nav, settings) {
// If nesting isn't activated, bail
if (!settings.nested) return;
// Get the parent navigation
var li = nav.parentNode.closest('li');
if (!li) return;
// Add the active class
li.classList.add(settings.nestedClass);
// Apply recursively to any parent navigation elements
activateNested(li, settings);
};
/**
* Activate a nav and content area
* @param {Object} items The nav item and content to activate
* @param {Object} settings The settings for this instantiation
*/
var activate = function (items, settings) {
// Make sure their are items to activate
if (!items) return;
// Get the parent list item
var li = items.nav.closest('li');
if (!li) return;
// Add the active class to the nav and content
li.classList.add(settings.navClass);
items.content.classList.add(settings.contentClass);
// Activate any parent navs in a nested navigation
activateNested(li, settings);
// Emit a custom event
emitEvent('gumshoeActivate', li, {
link: items.nav,
content: items.content,
settings: settings
});
};
/**
* Create the Constructor object
* @param {String} selector The selector to use for navigation items
* @param {Object} options User options and settings
*/
var Constructor = function (selector, options) {
//
// Variables
//
var publicAPIs = {};
var navItems, contents, current, timeout, settings;
//
// Methods
//
/**
* Set variables from DOM elements
*/
publicAPIs.setup = function () {
// Get all nav items
navItems = document.querySelectorAll(selector);
// Create contents array
contents = [];
// Loop through each item, get it's matching content, and push to the array
Array.prototype.forEach.call(navItems, (function (item) {
// Get the content for the nav item
var content = document.getElementById(decodeURIComponent(item.hash.substr(1)));
if (!content) return;
// Push to the contents array
contents.push({
nav: item,
content: content
});
}));
// Sort contents by the order they appear in the DOM
sortContents(contents);
};
/**
* Detect which content is currently active
*/
publicAPIs.detect = function () {
// Get the active content
var active = getActive(contents, settings);
// if there's no active content, deactivate and bail
if (!active) {
if (current) {
deactivate(current, settings);
current = null;
}
return;
}
// If the active content is the one currently active, do nothing
if (current && active.content === current.content) return;
// Deactivate the current content and activate the new content
deactivate(current, settings);
activate(active, settings);
// Update the currently active content
current = active;
};
/**
* Detect the active content on scroll
* Debounced for performance
*/
var scrollHandler = function (event) {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup debounce callback
timeout = window.requestAnimationFrame(publicAPIs.detect);
};
/**
* Update content sorting on resize
* Debounced for performance
*/
var resizeHandler = function (event) {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup debounce callback
timeout = window.requestAnimationFrame((function () {
sortContents();
publicAPIs.detect();
}));
};
/**
* Destroy the current instantiation
*/
publicAPIs.destroy = function () {
// Undo DOM changes
if (current) {
deactivate(current);
}
// Remove event listeners
window.removeEventListener('scroll', scrollHandler, false);
if (settings.reflow) {
window.removeEventListener('resize', resizeHandler, false);
}
// Reset variables
contents = null;
navItems = null;
current = null;
timeout = null;
settings = null;
};
/**
* Initialize the current instantiation
*/
var init = function () {
// Merge user options into defaults
settings = extend(defaults, options || {});
// Setup variables based on the current DOM
publicAPIs.setup();
// Find the currently active content
publicAPIs.detect();
// Setup event listeners
window.addEventListener('scroll', scrollHandler, false);
if (settings.reflow) {
window.addEventListener('resize', resizeHandler, false);
}
};
//
// Initialize and return the public APIs
//
init();
return publicAPIs;
};
//
// Return the Constructor
//
return Constructor;
}));

View file

@ -1,9 +0,0 @@
/*!
* jQuery Smooth Scroll - v2.2.0 - 2017-05-05
* https://github.com/kswedberg/jquery-smooth-scroll
* Copyright (c) 2017 Karl Swedberg
* Licensed MIT
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof module&&module.exports?require("jquery"):jQuery)}(function(a){var b={},c={exclude:[],excludeWithin:[],offset:0,direction:"top",delegateSelector:null,scrollElement:null,scrollTarget:null,autoFocus:!1,beforeScroll:function(){},afterScroll:function(){},easing:"swing",speed:400,autoCoefficient:2,preventDefault:!0},d=function(b){var c=[],d=!1,e=b.dir&&"left"===b.dir?"scrollLeft":"scrollTop";return this.each(function(){var b=a(this);if(this!==document&&this!==window)return!document.scrollingElement||this!==document.documentElement&&this!==document.body?void(b[e]()>0?c.push(this):(b[e](1),d=b[e]()>0,d&&c.push(this),b[e](0))):(c.push(document.scrollingElement),!1)}),c.length||this.each(function(){this===document.documentElement&&"smooth"===a(this).css("scrollBehavior")&&(c=[this]),c.length||"BODY"!==this.nodeName||(c=[this])}),"first"===b.el&&c.length>1&&(c=[c[0]]),c},e=/^([\-\+]=)(\d+)/;a.fn.extend({scrollable:function(a){var b=d.call(this,{dir:a});return this.pushStack(b)},firstScrollable:function(a){var b=d.call(this,{el:"first",dir:a});return this.pushStack(b)},smoothScroll:function(b,c){if("options"===(b=b||{}))return c?this.each(function(){var b=a(this),d=a.extend(b.data("ssOpts")||{},c);a(this).data("ssOpts",d)}):this.first().data("ssOpts");var d=a.extend({},a.fn.smoothScroll.defaults,b),e=function(b){var c=function(a){return a.replace(/(:|\.|\/)/g,"\\$1")},e=this,f=a(this),g=a.extend({},d,f.data("ssOpts")||{}),h=d.exclude,i=g.excludeWithin,j=0,k=0,l=!0,m={},n=a.smoothScroll.filterPath(location.pathname),o=a.smoothScroll.filterPath(e.pathname),p=location.hostname===e.hostname||!e.hostname,q=g.scrollTarget||o===n,r=c(e.hash);if(r&&!a(r).length&&(l=!1),g.scrollTarget||p&&q&&r){for(;l&&j<h.length;)f.is(c(h[j++]))&&(l=!1);for(;l&&k<i.length;)f.closest(i[k++]).length&&(l=!1)}else l=!1;l&&(g.preventDefault&&b.preventDefault(),a.extend(m,g,{scrollTarget:g.scrollTarget||r,link:e}),a.smoothScroll(m))};return null!==b.delegateSelector?this.off("click.smoothscroll",b.delegateSelector).on("click.smoothscroll",b.delegateSelector,e):this.off("click.smoothscroll").on("click.smoothscroll",e),this}});var f=function(a){var b={relative:""},c="string"==typeof a&&e.exec(a);return"number"==typeof a?b.px=a:c&&(b.relative=c[1],b.px=parseFloat(c[2])||0),b},g=function(b){var c=a(b.scrollTarget);b.autoFocus&&c.length&&(c[0].focus(),c.is(document.activeElement)||(c.prop({tabIndex:-1}),c[0].focus())),b.afterScroll.call(b.link,b)};a.smoothScroll=function(c,d){if("options"===c&&"object"==typeof d)return a.extend(b,d);var e,h,i,j,k=f(c),l={},m=0,n="offset",o="scrollTop",p={},q={};k.px?e=a.extend({link:null},a.fn.smoothScroll.defaults,b):(e=a.extend({link:null},a.fn.smoothScroll.defaults,c||{},b),e.scrollElement&&(n="position","static"===e.scrollElement.css("position")&&e.scrollElement.css("position","relative")),d&&(k=f(d))),o="left"===e.direction?"scrollLeft":o,e.scrollElement?(h=e.scrollElement,k.px||/^(?:HTML|BODY)$/.test(h[0].nodeName)||(m=h[o]())):h=a("html, body").firstScrollable(e.direction),e.beforeScroll.call(h,e),l=k.px?k:{relative:"",px:a(e.scrollTarget)[n]()&&a(e.scrollTarget)[n]()[e.direction]||0},p[o]=l.relative+(l.px+m+e.offset),i=e.speed,"auto"===i&&(j=Math.abs(p[o]-h[o]()),i=j/e.autoCoefficient),q={duration:i,easing:e.easing,complete:function(){g(e)}},e.step&&(q.step=e.step),h.length?h.stop().animate(p,q):g(e)},a.smoothScroll.version="2.2.0",a.smoothScroll.filterPath=function(a){return a=a||"",a.replace(/^\//,"").replace(/(?:index|default).[a-zA-Z]{3,4}$/,"").replace(/\/$/,"")},a.fn.smoothScroll.defaults=c});

632
assets/js/plugins/smooth-scroll.js vendored Normal file
View file

@ -0,0 +1,632 @@
/*!
* smooth-scroll v15.2.1
* Animate scrolling to anchor links
* (c) 2019 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/smooth-scroll
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], (function () {
return factory(root);
}));
} else if (typeof exports === 'object') {
module.exports = factory(root);
} else {
root.SmoothScroll = factory(root);
}
})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
'use strict';
//
// Default settings
//
var defaults = {
// Selectors
ignore: '[data-scroll-ignore]',
header: null,
topOnEmptyHash: true,
// Speed & Duration
speed: 500,
speedAsDuration: false,
durationMax: null,
durationMin: null,
clip: true,
offset: 0,
// Easing
easing: 'easeInOutCubic',
customEasing: null,
// History
updateURL: true,
popstate: true,
// Custom Events
emitEvents: true
};
//
// Utility Methods
//
/**
* Check if browser supports required methods
* @return {Boolean} Returns true if all required methods are supported
*/
var supports = function () {
return (
'querySelector' in document &&
'addEventListener' in window &&
'requestAnimationFrame' in window &&
'closest' in window.Element.prototype
);
};
/**
* Merge two or more objects together.
* @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
var extend = function () {
var merged = {};
Array.prototype.forEach.call(arguments, (function (obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) return;
merged[key] = obj[key];
}
}));
return merged;
};
/**
* Check to see if user prefers reduced motion
* @param {Object} settings Script settings
*/
var reduceMotion = function (settings) {
if ('matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches) {
return true;
}
return false;
};
/**
* Get the height of an element.
* @param {Node} elem The element to get the height of
* @return {Number} The element's height in pixels
*/
var getHeight = function (elem) {
return parseInt(window.getComputedStyle(elem).height, 10);
};
/**
* Escape special characters for use with querySelector
* @author Mathias Bynens
* @link https://github.com/mathiasbynens/CSS.escape
* @param {String} id The anchor ID to 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: theres 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 sanitized hash
return '#' + result;
};
/**
* Calculate the easing pattern
* @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 (settings, time) {
var pattern;
// Default Easing Patterns
if (settings.easing === 'easeInQuad') pattern = time * time; // accelerating from zero velocity
if (settings.easing === 'easeOutQuad') pattern = time * (2 - time); // decelerating to zero velocity
if (settings.easing === 'easeInOutQuad') pattern = time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
if (settings.easing === 'easeInCubic') pattern = time * time * time; // accelerating from zero velocity
if (settings.easing === 'easeOutCubic') pattern = (--time) * time * time + 1; // decelerating to zero velocity
if (settings.easing === 'easeInOutCubic') pattern = time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
if (settings.easing === 'easeInQuart') pattern = time * time * time * time; // accelerating from zero velocity
if (settings.easing === 'easeOutQuart') pattern = 1 - (--time) * time * time * time; // decelerating to zero velocity
if (settings.easing === 'easeInOutQuart') pattern = time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
if (settings.easing === 'easeInQuint') pattern = time * time * time * time * time; // accelerating from zero velocity
if (settings.easing === 'easeOutQuint') pattern = 1 + (--time) * time * time * time * time; // decelerating to zero velocity
if (settings.easing === 'easeInOutQuint') pattern = time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
// Custom Easing Patterns
if (!!settings.customEasing) pattern = settings.customEasing(time);
return pattern || time; // no easing, no acceleration
};
/**
* Determine the document's height
* @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
);
};
/**
* Calculate how far to scroll
* Clip support added by robjtede - https://github.com/cferdinandi/smooth-scroll/issues/405
* @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
* @param {Boolean} clip If true, adjust scroll distance to prevent abrupt stops near the bottom of the page
* @returns {Number}
*/
var getEndLocation = function (anchor, headerHeight, offset, clip) {
var location = 0;
if (anchor.offsetParent) {
do {
location += anchor.offsetTop;
anchor = anchor.offsetParent;
} while (anchor);
}
location = Math.max(location - headerHeight - offset, 0);
if (clip) {
location = Math.min(location, getDocumentHeight() - window.innerHeight);
}
return location;
};
/**
* Get the height of the fixed header
* @param {Node} header The header
* @return {Number} The height of the header
*/
var getHeaderHeight = function (header) {
return !header ? 0 : (getHeight(header) + header.offsetTop);
};
/**
* Calculate the speed to use for the animation
* @param {Number} distance The distance to travel
* @param {Object} settings The plugin settings
* @return {Number} How fast to animate
*/
var getSpeed = function (distance, settings) {
var speed = settings.speedAsDuration ? settings.speed : Math.abs(distance / 1000 * settings.speed);
if (settings.durationMax && speed > settings.durationMax) return settings.durationMax;
if (settings.durationMin && speed < settings.durationMin) return settings.durationMin;
return parseInt(speed, 10);
};
var setHistory = function (options) {
// Make sure this should run
if (!history.replaceState || !options.updateURL || history.state) return;
// Get the hash to use
var hash = window.location.hash;
hash = hash ? hash : '';
// Set a default history
history.replaceState(
{
smoothScroll: JSON.stringify(options),
anchor: hash ? hash : window.pageYOffset
},
document.title,
hash ? hash : window.location.href
);
};
/**
* Update the URL
* @param {Node} anchor The anchor that was scrolled to
* @param {Boolean} isNum If true, anchor is a number
* @param {Object} options Settings for Smooth Scroll
*/
var updateURL = function (anchor, isNum, options) {
// Bail if the anchor is a number
if (isNum) return;
// Verify that pushState is supported and the updateURL option is enabled
if (!history.pushState || !options.updateURL) return;
// Update URL
history.pushState(
{
smoothScroll: JSON.stringify(options),
anchor: anchor.id
},
document.title,
anchor === document.documentElement ? '#top' : '#' + anchor.id
);
};
/**
* Bring the anchored element into focus
* @param {Node} anchor The anchor element
* @param {Number} endLocation The end location to scroll to
* @param {Boolean} isNum If true, scroll is to a position rather than an element
*/
var adjustFocus = function (anchor, endLocation, isNum) {
// Is scrolling to top of page, blur
if (anchor === 0) {
document.body.focus();
}
// 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 !== anchor) {
anchor.setAttribute('tabindex', '-1');
anchor.focus();
anchor.style.outline = 'none';
}
window.scrollTo(0 , endLocation);
};
/**
* Emit a custom event
* @param {String} type The event type
* @param {Object} options The settings object
* @param {Node} anchor The anchor element
* @param {Node} toggle The toggle element
*/
var emitEvent = function (type, options, anchor, toggle) {
if (!options.emitEvents || typeof window.CustomEvent !== 'function') return;
var event = new CustomEvent(type, {
bubbles: true,
detail: {
anchor: anchor,
toggle: toggle
}
});
document.dispatchEvent(event);
};
//
// SmoothScroll Constructor
//
var SmoothScroll = function (selector, options) {
//
// Variables
//
var smoothScroll = {}; // Object for public APIs
var settings, anchor, toggle, fixedHeader, eventTimeout, animationInterval;
//
// Methods
//
/**
* Cancel a scroll-in-progress
*/
smoothScroll.cancelScroll = function (noEvent) {
cancelAnimationFrame(animationInterval);
animationInterval = null;
if (noEvent) return;
emitEvent('scrollCancel', settings);
};
/**
* Start/stop the scrolling animation
* @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) {
// Cancel any in progress scrolls
smoothScroll.cancelScroll();
// Local settings
var _settings = extend(settings || defaults, options || {}); // 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 = window.pageYOffset; // Current location on the page
if (_settings.header && !fixedHeader) {
// Get the fixed header if not already set
fixedHeader = document.querySelector(_settings.header);
}
var headerHeight = getHeaderHeight(fixedHeader);
var endLocation = isNum ? anchor : getEndLocation(anchorElem, headerHeight, parseInt((typeof _settings.offset === 'function' ? _settings.offset(anchor, toggle) : _settings.offset), 10), _settings.clip); // Location to scroll to
var distance = endLocation - startLocation; // distance to travel
var documentHeight = getDocumentHeight();
var timeLapsed = 0;
var speed = getSpeed(distance, _settings);
var start, percentage, position;
/**
* Stop the scroll animation when it reaches its target (or the bottom/top of page)
* @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) {
// Get the current location
var currentLocation = window.pageYOffset;
// Check if the end location has been reached yet (or we've hit the end of the document)
if (position == endLocation || currentLocation == endLocation || ((startLocation < endLocation && window.innerHeight + currentLocation) >= documentHeight)) {
// Clear the animation timer
smoothScroll.cancelScroll(true);
// Bring the anchored element into focus
adjustFocus(anchor, endLocation, isNum);
// Emit a custom event
emitEvent('scrollStop', _settings, anchor, toggle);
// Reset start
start = null;
animationInterval = null;
return true;
}
};
/**
* Loop scrolling animation
*/
var loopAnimateScroll = function (timestamp) {
if (!start) { start = timestamp; }
timeLapsed += timestamp - start;
percentage = speed === 0 ? 0 : (timeLapsed / speed);
percentage = (percentage > 1) ? 1 : percentage;
position = startLocation + (distance * easingPattern(_settings, percentage));
window.scrollTo(0, Math.floor(position));
if (!stopAnimateScroll(position, endLocation)) {
animationInterval = window.requestAnimationFrame(loopAnimateScroll);
start = timestamp;
}
};
/**
* Reset position to fix weird iOS bug
* @link https://github.com/cferdinandi/smooth-scroll/issues/45
*/
if (window.pageYOffset === 0) {
window.scrollTo(0, 0);
}
// Update the URL
updateURL(anchor, isNum, _settings);
// Emit a custom event
emitEvent('scrollStart', _settings, anchor, toggle);
// Start scrolling animation
smoothScroll.cancelScroll(true);
window.requestAnimationFrame(loopAnimateScroll);
};
/**
* If smooth scroll element clicked, animate scroll
*/
var clickHandler = function (event) {
// Don't run if the user prefers reduced motion
if (reduceMotion(settings)) return;
// Don't run if right-click or command/control + click
if (event.button !== 0 || event.metaKey || event.ctrlKey) return;
// Check if event.target has closest() method
// By @totegi - https://github.com/cferdinandi/smooth-scroll/pull/401/
if(!('closest' in event.target))return;
// Check if a smooth scroll link was clicked
toggle = event.target.closest(selector);
if (!toggle || toggle.tagName.toLowerCase() !== 'a' || event.target.closest(settings.ignore)) return;
// Only run if link is an anchor and points to the current page
if (toggle.hostname !== window.location.hostname || toggle.pathname !== window.location.pathname || !/#/.test(toggle.href)) return;
// Get an escaped version of the hash
var hash = escapeCharacters(toggle.hash);
// Get the anchored element
var anchor = settings.topOnEmptyHash && hash === '#' ? document.documentElement : document.querySelector(hash);
anchor = !anchor && hash === '#top' ? document.documentElement : anchor;
// If anchored element exists, scroll to it
if (!anchor) return;
event.preventDefault();
setHistory(settings);
smoothScroll.animateScroll(anchor, toggle);
};
/**
* Animate scroll on popstate events
*/
var popstateHandler = function (event) {
// Stop if history.state doesn't exist (ex. if clicking on a broken anchor link).
// fixes `Cannot read property 'smoothScroll' of null` error getting thrown.
if (history.state === null) return;
// Only run if state is a popstate record for this instantiation
if (!history.state.smoothScroll || history.state.smoothScroll !== JSON.stringify(settings)) return;
// Only run if state includes an anchor
// if (!history.state.anchor && history.state.anchor !== 0) return;
// Get the anchor
var anchor = history.state.anchor;
if (typeof anchor === 'string' && anchor) {
anchor = document.querySelector(escapeCharacters(history.state.anchor));
if (!anchor) return;
}
// Animate scroll to anchor link
smoothScroll.animateScroll(anchor, null, {updateURL: false});
};
/**
* Destroy the current initialization.
*/
smoothScroll.destroy = function () {
// If plugin isn't already initialized, stop
if (!settings) return;
// Remove event listeners
document.removeEventListener('click', clickHandler, false);
window.removeEventListener('popstate', popstateHandler, false);
// Cancel any scrolls-in-progress
smoothScroll.cancelScroll();
// Reset variables
settings = null;
anchor = null;
toggle = null;
fixedHeader = null;
eventTimeout = null;
animationInterval = null;
};
/**
* Initialize Smooth Scroll
* @param {Object} options User settings
*/
smoothScroll.init = function (options) {
// feature test
if (!supports()) throw 'Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.';
// Destroy any existing initializations
smoothScroll.destroy();
// Selectors and variables
settings = extend(defaults, options || {}); // Merge user options with defaults
fixedHeader = settings.header ? document.querySelector(settings.header) : null; // Get the fixed header
// When a toggle is clicked, run the click handler
document.addEventListener('click', clickHandler, false);
// If updateURL and popState are enabled, listen for pop events
if (settings.updateURL && settings.popstate) {
window.addEventListener('popstate', popstateHandler, false);
}
};
//
// Initialize plugin
//
smoothScroll.init(options);
//
// Public APIs
//
return smoothScroll;
};
return SmoothScroll;
}));

View file

@ -26,7 +26,7 @@
"uglify-js": "^3.4.9"
},
"scripts": {
"uglify": "uglifyjs assets/js/vendor/jquery/jquery-3.3.1.min.js assets/js/plugins/jquery.fitvids.js assets/js/plugins/jquery.greedy-navigation.js assets/js/plugins/jquery.magnific-popup.js assets/js/plugins/jquery.smooth-scroll.min.js assets/js/plugins/jquery.ba-throttle-debounce.js assets/js/_main.js -c -m -o assets/js/main.min.js",
"uglify": "uglifyjs assets/js/vendor/jquery/jquery-3.3.1.min.js assets/js/plugins/jquery.fitvids.js assets/js/plugins/jquery.greedy-navigation.js assets/js/plugins/jquery.magnific-popup.js assets/js/plugins/jquery.ba-throttle-debounce.js assets/js/plugins/smooth-scroll.js assets/js/plugins/gumshoe.js assets/js/_main.js -c -m -o assets/js/main.min.js",
"add-banner": "node banner.js",
"watch:js": "onchange \"assets/js/**/*.js\" -e \"assets/js/main.min.js\" -- npm run build:js",
"build:js": "npm run uglify && npm run add-banner"

View file

@ -10,7 +10,9 @@ tags:
You'll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in [many different ways](https://jekyllrb.com/docs/usage/), but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.
To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
To add new posts, simply add a file in the `_posts`[^posts] directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
[^posts]: Footnote test.
Jekyll also offers powerful support for code snippets: