From cb09b7ce1eaaba6700092993e153a83e28ebe641 Mon Sep 17 00:00:00 2001 From: Xin Date: Thu, 12 Oct 2023 23:25:34 +0100 Subject: [PATCH] fix: skip scroll event if no backToTop element (#138) --- assets/js/back-to-top.js | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/assets/js/back-to-top.js b/assets/js/back-to-top.js index c7996e74..df6f1be1 100644 --- a/assets/js/back-to-top.js +++ b/assets/js/back-to-top.js @@ -1,18 +1,22 @@ -const backToTop = document.querySelector("#backToTop"); +// Back to top button -document.addEventListener("scroll", (event) => { - if (window.scrollY > 300) { - backToTop.classList.remove("opacity-0"); - } else { - backToTop.classList.add("opacity-0"); +document.addEventListener("DOMContentLoaded", function () { + const backToTop = document.querySelector("#backToTop"); + if (backToTop) { + document.addEventListener("scroll", (e) => { + if (window.scrollY > 300) { + backToTop.classList.remove("opacity-0"); + } else { + backToTop.classList.add("opacity-0"); + } + }); } }); - function scrollUp() { window.scroll({ - top: 0, - left: 0, - behavior: 'smooth' + top: 0, + left: 0, + behavior: "smooth", }); }