Skip to content

Commit 7fcd00c

Browse files
committed
Added ScrollToTop.svelte and into layout
1 parent c50f768 commit 7fcd00c

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<script lang="ts">
2+
import { onMount } from "svelte";
3+
import { fly } from "svelte/transition";
4+
5+
let y = 0;
6+
let hasMounted = false; // This is false on the server and for no-JS users
7+
8+
// This reactive variable is only relevant for JS users
9+
$: showButton = y > 200;
10+
11+
// This only runs in the browser
12+
onMount(() => {
13+
hasMounted = true;
14+
});
15+
16+
// This click handler adds smooth scrolling for JS users
17+
const smoothScroll = (event: MouseEvent) => {
18+
event.preventDefault();
19+
window.scrollTo({ top: 0, behavior: "smooth" });
20+
};
21+
</script>
22+
23+
<!-- Listen to the window's scroll position -->
24+
<svelte:window bind:scrollY={y} />
25+
26+
<!--
27+
- For No-JS users: `hasMounted` is false, so the button is always visible.
28+
- For JS users: `hasMounted` is true, so the button is only visible when `showButton` is true.
29+
-->
30+
{#if !hasMounted || showButton}
31+
<a
32+
href="#page-top"
33+
on:click={smoothScroll}
34+
transition:fly={{ y: 100, duration: 300 }}
35+
class="fixed bottom-8 right-8 z-50 flex h-14 w-14 items-center justify-center rounded-full bg-ctp-mauve text-ctp-base shadow-lg transition-all hover:scale-110 hover:bg-ctp-pink focus:outline-none focus:ring-2 focus:ring-ctp-pink focus:ring-offset-2 focus:ring-offset-ctp-base"
36+
aria-label="Scroll to top"
37+
>
38+
<!-- SVG arrow icon -->
39+
<svg
40+
xmlns="http://www.w3.org/2000/svg"
41+
viewBox="0 0 24 24"
42+
fill="none"
43+
stroke="currentColor"
44+
stroke-width="3"
45+
stroke-linecap="round"
46+
stroke-linejoin="round"
47+
class="h-6 w-6"
48+
>
49+
<path d="M12 19V5M5 12l7-7 7 7" />
50+
</svg>
51+
</a>
52+
{/if}

src/routes/+layout.svelte

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import { theme } from "$lib/stores/theme";
66
import { language } from "$lib/stores/language";
77
import { browser } from "$app/environment";
8+
import ScrollToTop from "$lib/components/ScrollToTop.svelte";
89
910
theme.init();
1011
language.init();
@@ -20,6 +21,7 @@
2021
class:font-hebrew={$language === "he"}
2122
>
2223
<div
24+
id="page-top"
2325
class="container mx-auto max-w-5xl bg-ctp-base p-4 shadow-2xl shadow-ctp-crust"
2426
>
2527
<Header />
@@ -28,4 +30,5 @@
2830
</main>
2931
<Footer />
3032
</div>
33+
<ScrollToTop />
3134
</div>

0 commit comments

Comments
 (0)