|
| 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} |
0 commit comments