diff --git a/js/back-to-top.js b/js/back-to-top.js index 4dc4e91..d661a9a 100644 --- a/js/back-to-top.js +++ b/js/back-to-top.js @@ -2,7 +2,7 @@ * @file Drupal behavior for 'back to top' link. */ -(function (Drupal) { +(function localgovBackToTopScript(Drupal) { Drupal.behaviors.localgovBackToTop = { attach(context) { /** @@ -19,28 +19,29 @@ * past the top of the viewport. In practices, there's only one of * these since we've only targeted one element. */ + const [backToTop] = once('back-to-top', '.back-to-top', context); + const [backToTopTarget] = once( + 'back-to-top-target', + '.back-to-top-target', + context, + ); + function observerCallback(entries) { entries.forEach((entry) => { - backToTop.hidden = ( + backToTop.hidden = entry.isIntersecting || (!entry.isIntersecting && entry.boundingClientRect.top <= 0) - ) ? false : 'until-hidden'; + ? false + : 'until-hidden'; }); } - const [backToTop] = once('back-to-top', '.back-to-top', context); - const [backToTopTarget] = once( - 'back-to-top-target', - '.back-to-top-target', - context, - ); const minContentViewportRatio = parseFloat( backToTop?.dataset?.minContentViewportRatio ?? 1.5, 10, ); const viewportHeight = window.innerHeight; const documentHeight = document.documentElement.offsetHeight; - let intersectionObserver; if ( !backToTop || @@ -53,10 +54,12 @@ // Create an element absolutely positioned at our threshold. backToTopTarget.style.position = 'absolute'; backToTopTarget.style.top = `${viewportHeight * minContentViewportRatio}px`; - backToTop.addEventListener('click', (event) => event.target.hidden = 'until-found'); + backToTop.addEventListener('click', (event) => { + event.target.hidden = 'until-found'; + }); // Create an IntersectionObserver. - intersectionObserver = new IntersectionObserver(observerCallback, { + const intersectionObserver = new IntersectionObserver(observerCallback, { rootMargin: '16px', }); intersectionObserver.observe(backToTopTarget);