From 6a66cdaf22e4994cd6a95af280f0906404e9b33c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Tue, 19 Jul 2022 13:43:25 +0200 Subject: [PATCH] Use options parameters with types and default on smoothScroll function --- src/components/molecules/Poster.svelte | 2 +- .../molecules/ShopLocationSwitcher.svelte | 2 +- src/components/organisms/ShopHeader.svelte | 2 +- src/routes/index.svelte | 2 +- src/utils/functions/index.ts | 16 +++++++++++----- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/components/molecules/Poster.svelte b/src/components/molecules/Poster.svelte index f13e0da..1ce0163 100644 --- a/src/components/molecules/Poster.svelte +++ b/src/components/molecules/Poster.svelte @@ -36,7 +36,7 @@ size="xsmall" url="/shop/poster-{location.slug}" text="View" - on:click={() => setTimeout(() => smoothScroll('poster', false), 1000)} + on:click={() => setTimeout(() => smoothScroll({ hash: 'poster', changeHash: false }), 1000)} /> diff --git a/src/utils/functions/index.ts b/src/utils/functions/index.ts index 1285fc9..4d992cc 100644 --- a/src/utils/functions/index.ts +++ b/src/utils/functions/index.ts @@ -158,7 +158,7 @@ export const scrollToTop = (delay?: number) => { /** * Smooth Scroll to an element * @description Promised based - * @url https://www.youtube.com/watch?v=oUSvlrDTLi4 + * @url Based on: https://www.youtube.com/watch?v=oUSvlrDTLi4 */ const smoothScrollPromise = (target: HTMLElement, duration: number = 1600): Promise => { const position = target.getBoundingClientRect().top + 1 @@ -190,13 +190,19 @@ const smoothScrollPromise = (target: HTMLElement, duration: number = 1600): Prom requestAnimationFrame(animation) }) } -export const smoothScroll = async (hash: string, changeHash: boolean = true, callback?: Function) => { +export const smoothScroll = async ({ hash, callback, changeHash = true, event }: smoothScrollOptions) => { + if (event) event.preventDefault() + const target = document.getElementById(hash) smoothScrollPromise(target).then(() => { - if (changeHash) { - location.hash = hash - } + if (changeHash) location.hash = hash callback && callback() }) +} +type smoothScrollOptions = { + hash: string + changeHash?: boolean + event?: MouseEvent + callback?: Function } \ No newline at end of file