mercury/src/components/BackToTop.astro

40 lines
No EOL
1.6 KiB
Text

---
import {siteConfig} from "../config";
import { getLangFromUrl, useTranslations, useTranslatedPath } from '../i18n/utils';
const lang = getLangFromUrl(Astro.url);
const t = useTranslations(lang);
const translatePath = useTranslatedPath(lang);
const noscript = siteConfig.noClientJavaScript
---
{noscript ? <a href="#top"><button id="toTopBtn" style="display: block" title={t('widget.back_to_top.title')}>{t('widget.back_to_top')}</button></a> : <button id="toTopBtn" title={t('widget.back_to_top.title')}>{t('widget.back_to_top')}</button>
<script>
// Get the button
let toTopButton = document.getElementById("toTopBtn");
// When the user scrolls down from the top of the document, show the button
window.addEventListener("scroll", ()=> {
if (window.scrollY < document.documentElement.clientHeight) {
toTopButton.classList.remove('fade-in');
toTopButton.classList.add('fade-out');
toTopButton.style.display = 'block';
} else {
toTopButton.classList.remove('fade-out');
toTopButton.classList.remove('fade-in');
}
})
// When the user clicks on the button, scroll to the top of the document
toTopButton.addEventListener("click", toTop);
function toTop() {
try {
// scrollback gracefully
window.scrollTo({top: 0, behavior: 'smooth'});
} catch (e) {
// if there is a error,return to top directly
console.error(e);
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
}
</script>}