From 6fcecce3111ac6a46467499174cbf4abc5759fe7 Mon Sep 17 00:00:00 2001 From: codl Date: Thu, 12 Apr 2018 04:43:22 +0200 Subject: [PATCH] allow scroll-to-top to be canceled by a user scroll (#79) --- routes/_utils/smoothScrollToTop.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/routes/_utils/smoothScrollToTop.js b/routes/_utils/smoothScrollToTop.js index 76e596e..fd5b051 100644 --- a/routes/_utils/smoothScrollToTop.js +++ b/routes/_utils/smoothScrollToTop.js @@ -13,7 +13,12 @@ const scroll = (node, key, target) => { const elapsed = Date.now() - startTime const percentage = elapsed / duration - if (percentage > 1 || interrupt) { + if (interrupt) { + return + } + + if (percentage > 1) { + cleanup() return } @@ -21,11 +26,22 @@ const scroll = (node, key, target) => { requestAnimationFrame(step) } + const cancel = () => { + interrupt = true + cleanup() + } + + const cleanup = () => { + node.removeEventListener('wheel', cancel) + node.removeEventListener('touchstart', cancel) + } + + node.addEventListener('wheel', cancel, {passive: true}) + node.addEventListener('touchstart', cancel, {passive: true}) + step() - return () => { - interrupt = true - } + return cancel } export const smoothScrollToTop = node => scroll(node, 'scrollTop', 0)