Building a Back to Top button with IntersectionObserver and Svelte

main.js
1
2
3
4
5
6
7
8
9
10
11
import BackToTop from './components/BackToTop.svelte'

// Back to Top button
if ('IntersectionObserver' in window) {
new BackToTop({
target: document.querySelector('#backtotop'),
props: {
track: document.querySelector("#search")
}
})
}
BackToTop.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script>
import { fade } from 'svelte/transition'
export let track

let visible = false

new IntersectionObserver(entries => {
entries[0].intersectionRatio > 0 ?
visible = false :
visible = true
}).observe(track)

function scrollUp() {
document.body.scrollIntoView({behavior: "smooth"})
}
</script>

{#if visible}
<button
transition:fade
on:click={scrollUp}
class="btn bg-orange-700 hover:bg-orange-800 hover:shadow-lg text-white fixed bottom-0 right-0 mb-3 mr-3"
>
Back to Top
</button>
{/if}