From 618d2699c55cd9d9e58157af842d054f6aba02e3 Mon Sep 17 00:00:00 2001 From: youhavetrouble Date: Thu, 28 Dec 2023 23:51:51 +0100 Subject: [PATCH] fix mobile section observer --- index.js | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/index.js b/index.js index 4659fd3..1db0de7 100644 --- a/index.js +++ b/index.js @@ -1,25 +1,37 @@ const sections = document.querySelectorAll('main section'); const navLinks = document.querySelectorAll('[data-link]'); -const options = { +const observer = new IntersectionObserver((entries) => { + if (window.innerWidth <= 767) return; + entries.forEach(entry => { + if (entry.isIntersecting) { + const sectionId = entry.target.id; + setActiveLink(sectionId); + } + }); +}, { root: null, rootMargin: '-20% 0px -20% 0px', - threshold: 0.2 -}; + threshold: 0.3 +}); -const observer = new IntersectionObserver((entries, observer) => { +const mobileObserver = new IntersectionObserver((entries) => { + if (window.innerWidth > 767) return; entries.forEach(entry => { - entries.forEach(entry => { - if (entry.isIntersecting) { - const sectionId = entry.target.id; - setActiveLink(sectionId); - } - }); + if (entry.isIntersecting) { + const sectionId = entry.target.id; + setActiveLink(sectionId); + } }); -}, options); +}, { + root: null, + rootMargin: '-30% 0px -30% 0px', + threshold: 0.1 +}); sections.forEach(section => { observer.observe(section); + mobileObserver.observe(section); }); function setActiveLink(sectionId) {