From 4b028b1a622f6949399b30f56b840e379e6c676b Mon Sep 17 00:00:00 2001 From: Nolan Lawson Date: Fri, 7 Dec 2018 08:20:16 -0800 Subject: [PATCH] fix: use native smooth scroll when possible (#751) --- routes/_components/NavItem.html | 2 +- routes/_utils/smoothScrollToTop.js | 32 ++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/routes/_components/NavItem.html b/routes/_components/NavItem.html index 4bdf6da8..1f5b36fd 100644 --- a/routes/_components/NavItem.html +++ b/routes/_components/NavItem.html @@ -224,4 +224,4 @@ } } } - \ No newline at end of file + diff --git a/routes/_utils/smoothScrollToTop.js b/routes/_utils/smoothScrollToTop.js index 7ff05e38..4a22d3f0 100644 --- a/routes/_utils/smoothScrollToTop.js +++ b/routes/_utils/smoothScrollToTop.js @@ -2,7 +2,7 @@ const easingOutQuint = (x, t, b, c, d) => c * ((t = t / d - 1) * t * t * t * t + 1) + b -const scroll = (node, key, target) => { +function smoothScrollPolyfill (node, key, target) { const startTime = Date.now() const offset = node[key] const gap = target - offset @@ -44,4 +44,32 @@ const scroll = (node, key, target) => { return cancel } -export const smoothScrollToTop = node => scroll(node, 'scrollTop', 0) +function testSupportsSmoothScroll () { + let supports = false + try { + let div = document.createElement('div') + div.scrollTo({ + top: 0, + get behavior () { + supports = true + return 'smooth' + } + }) + } catch (err) {} // Edge throws an error + return supports +} + +const smoothScrollSupported = process.browser && testSupportsSmoothScroll() + +export function smoothScrollToTop (node) { + if (smoothScrollSupported) { + console.log('using native smooth scroll') + return node.scrollTo({ + top: 0, + behavior: 'smooth' + }) + } else { + console.log('using polyfilled smooth scroll') + return smoothScrollPolyfill(node, 'scrollTop', 0) + } +}