blakerain.com/layouts/partials/goto-top.html

62 lines
1.7 KiB
HTML

<button
id="goto-top"
type="button"
tabindex="-1"
class="button fixed bottom-8 right-8 opacity-25 hover:opacity-100 print:hidden hidden">
&#8593;<span class="hidden lg:inline"> Goto Top</span>
</button>
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function() {
const header = document.querySelector("nav:first-of-type");
const footer = document.querySelector("footer");
const button = document.getElementById('goto-top');
const visible = { nav: false, footer: false };
button.addEventListener("click", () => {
window.scrollTo({ top: 0, behavior: "smooth" });
});
function getButtonTransform() {
if (visible.footer) {
if (footer) {
const height = -footer.getBoundingClientRect().height;
return `transform: translateY(${height}px)`;
} else {
return "transform: translateY(-10px)";
}
} else if (!visible.nav) {
return "transform: translateY(0px)";
} else {
return "transform: translateY(100px)";
}
}
function updateButton() {
if (visible.nav) {
button.classList.remove("md:block");
} else {
button.classList.add("md:block");
}
button.style = getButtonTransform();
}
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
const tagName = entry.target.tagName;
if (tagName == "NAV") {
visible.nav = entry.isIntersecting;
} else if (tagName == "FOOTER") {
visible.footer = entry.isIntersecting;
}
});
updateButton();
});
observer.observe(header);
observer.observe(footer);
updateButton();
});
</script>