Make scroll-to-top button its own WebC component

This commit is contained in:
Helen Chong 2024-04-11 23:42:11 +08:00
parent 846201701b
commit 35e9c3bd7d
4 changed files with 52 additions and 38 deletions

View File

@ -33,16 +33,11 @@
{# JavaScript #} {# JavaScript #}
<script src="/assets/js/navbar.js" defer></script> <script src="/assets/js/navbar.js" defer></script>
<script src="/assets/js/events.js" defer></script> <script src="/assets/js/events.js" defer></script>
<script src="/assets/js/scroll.js" defer></script>
{% if toc %} <script src="/assets/js/toc.js" defer></script> {% endif %} {% if toc %} <script src="/assets/js/toc.js" defer></script> {% endif %}
<title>{{ title }} | Leilukin's Hub</title> <title>{{ title }} | Leilukin's Hub</title>
</head> </head>
<body> <body>
<button class="top-btn hidden" aria-label="Scroll to top">
<img src="/assets/images/elements/top.svg" alt="">
</button>
{% include "main/header.njk" %} {% include "main/header.njk" %}
{% include "main/navbar.njk" %} {% include "main/navbar.njk" %}
<main> <main>
@ -57,5 +52,8 @@
</aside> --> </aside> -->
</main> </main>
{% include "main/footer.njk" %} {% include "main/footer.njk" %}
{% renderTemplate "webc" %}
<top-btn></top-btn>
{% endrenderTemplate %}
</body> </body>
</html> </html>

View File

@ -0,0 +1,49 @@
<button class="top-btn hidden" aria-label="Scroll to top">
<img src="/assets/images/elements/top.svg" alt="">
</button>
<style webc:keep webc:bucket="defer">
:root {
--clr-top-btn: #FFD05A;
}
.top-btn {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 999;
border: none;
background-color: var(--clr-top-btn);
border-radius: 50em;
padding: 0.5em;
}
.top-btn:focus {
outline: 0.25em solid var(--clr-top-btn);
outline-offset: 0.15em;
}
.top-btn img {
width: 2rem;
}
</style>
<script webc:keep webc:bucket="defer">
const topButton = document.querySelector(".top-btn");
window.onscroll = () => {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
topButton.classList.remove("hidden");
} else {
topButton.classList.add("hidden");
}
}
topButton.addEventListener('click', () => {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth",
});
});
</script>

View File

@ -229,22 +229,6 @@ dd {
grid-column-start: 2; grid-column-start: 2;
} }
/* Scrool to Top Button */
.top-btn {
position: fixed;
bottom: 20px;
right: 30px;
z-index: 999;
border: none;
background-color: var(--clr-top-btn);
border-radius: 0.2em;
padding: 0.4em;
}
.top-btn img {
width: 1.6rem;
}
/* HEADER COMPONENT */ /* HEADER COMPONENT */
.main-header { .main-header {
width: 100%; width: 100%;

View File

@ -1,17 +0,0 @@
const topButton = document.querySelector(".top-btn");
window.onscroll = () => {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
topButton.classList.remove("hidden");
} else {
topButton.classList.add("hidden");
}
}
topButton.addEventListener('click', () => {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth",
});
});