diff options
Diffstat (limited to 'docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/smoothscroll.js')
-rw-r--r-- | docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/smoothscroll.js | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/smoothscroll.js b/docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/smoothscroll.js new file mode 100644 index 000000000..4bb2d99b8 --- /dev/null +++ b/docs/_vendor/github.com/gohugoio/gohugoioTheme/assets/js/smoothscroll.js @@ -0,0 +1,80 @@ +// query selector targets Hugo TOC +(function() { + + 'use strict'; + + // Feature Test + if ('querySelector' in document && 'addEventListener' in window && Array.prototype.forEach) { + + // Function to animate the scroll + var smoothScroll = function(anchor, duration) { + + // Calculate how far and how fast to scroll + var startLocation = window.pageYOffset; + var endLocation = anchor.offsetTop; + var distance = endLocation - startLocation; + var increments = distance / (duration / 16); + var stopAnimation; + + // Scroll the page by an increment, and check if it's time to stop + var animateScroll = function() { + window.scrollBy(0, increments); + stopAnimation(); + }; + + // If scrolling down + if (increments >= 0) { + // Stop animation when you reach the anchor OR the bottom of the page + stopAnimation = function() { + var travelled = window.pageYOffset; + if ((travelled >= (endLocation - increments)) || ((window.innerHeight + travelled) >= document.body.offsetHeight)) { + clearInterval(runAnimation); + } + }; + } + // If scrolling up + else { + // Stop animation when you reach the anchor OR the top of the page + stopAnimation = function() { + var travelled = window.pageYOffset; + if (travelled <= (endLocation || 0)) { + clearInterval(runAnimation); + } + }; + } + + // Loop the animation function + var runAnimation = setInterval(animateScroll, 16); + + }; + + // Define smooth scroll links + var scrollToggle = document.querySelectorAll('#TableOfContents ul li a'); + + // For each smooth scroll link + [].forEach.call(scrollToggle, function(toggle) { + + // When the smooth scroll link is clicked + toggle.addEventListener('click', function(e) { + + // Prevent the default link behavior + e.preventDefault(); + + // Get anchor link and calculate distance from the top + var dataID = toggle.getAttribute('href'); + var dataTarget = document.querySelector(dataID); + var dataSpeed = toggle.getAttribute('data-speed'); + + // If the anchor exists + if (dataTarget) { + // Scroll to the anchor + smoothScroll(dataTarget, dataSpeed || 500); + } + + }, false); + + }); + + } + +})(); |