Smooth scroll to anchor without a library

Custom function using scrollIntoView with smooth behavior
This commit is contained in:
2020-04-07 18:47:02 +02:00
parent 1a05c35fc8
commit c5836dcbc1
4 changed files with 16 additions and 13 deletions

View File

@@ -24,8 +24,7 @@
"polka": "^1.0.0-next.9", "polka": "^1.0.0-next.9",
"scroll-out": "^2.2.8", "scroll-out": "^2.2.8",
"sirv": "^0.4.2", "sirv": "^0.4.2",
"swipe-listener": "^1.1.0", "swipe-listener": "^1.1.0"
"zenscroll": "^4.0.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.9.0", "@babel/core": "^7.9.0",

6
pnpm-lock.yaml generated
View File

@@ -8,7 +8,6 @@ dependencies:
scroll-out: 2.2.8 scroll-out: 2.2.8
sirv: 0.4.2 sirv: 0.4.2
swipe-listener: 1.1.0 swipe-listener: 1.1.0
zenscroll: 4.0.2
devDependencies: devDependencies:
'@babel/core': 7.9.0 '@babel/core': 7.9.0
'@babel/plugin-syntax-dynamic-import': 7.8.3_@babel+core@7.9.0 '@babel/plugin-syntax-dynamic-import': 7.8.3_@babel+core@7.9.0
@@ -4850,10 +4849,6 @@ packages:
dev: true dev: true
resolution: resolution:
integrity: sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg= integrity: sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=
/zenscroll/4.0.2:
dev: false
resolution:
integrity: sha1-6NV3TRwHOKR7z6hynzcS4t7d6yU=
specifiers: specifiers:
'@babel/core': ^7.9.0 '@babel/core': ^7.9.0
'@babel/plugin-syntax-dynamic-import': ^7.8.3 '@babel/plugin-syntax-dynamic-import': ^7.8.3
@@ -4896,4 +4891,3 @@ specifiers:
svelte: ^3.20.1 svelte: ^3.20.1
svelte-preprocess: ^3.7.1 svelte-preprocess: ^3.7.1
swipe-listener: ^1.1.0 swipe-listener: ^1.1.0
zenscroll: ^4.0.2

View File

@@ -30,10 +30,7 @@
currentPhotos, currentPhotos,
pageReady pageReady
} from 'utils/store' } from 'utils/store'
import { charsToSpan } from 'utils/functions' import { charsToSpan, smoothScroll } from 'utils/functions'
// Dependencies
import zenscroll from 'zenscroll'
// Components // Components
import Button from 'atoms/Button' import Button from 'atoms/Button'
@@ -93,7 +90,7 @@
<div class="intro__description style-description"> <div class="intro__description style-description">
<p>{$site.description}</p> <p>{$site.description}</p>
<Button type="a" href="#choose" class="button" text="Explore locations"> <Button type="a" href="#choose" class="button" text="Explore locations" on:click={smoothScroll}>
<IconGlobeSmall width="22" color="#666" /> <IconGlobeSmall width="22" color="#666" />
</Button> </Button>
</div> </div>

View File

@@ -179,6 +179,19 @@ export const parallaxAnime = (element, anime) => {
} }
/*
** Smooth scroll to anchor on click
*/
export const smoothScroll = event => {
const link = event.target.closest('a')
const hash = link.getAttribute('href').split('#')[1]
const target = document.getElementById(hash)
target.scrollIntoView({ behavior: 'smooth' })
history.pushState({}, null, `#${hash}`)
event.preventDefault()
}
/* /*
** Google Analytics send page ** Google Analytics send page
*/ */