From bdad1a0e312a33a2e015790619fdadad69d58fd5 Mon Sep 17 00:00:00 2001 From: doup Date: Thu, 5 Dec 2024 22:53:03 +0100 Subject: [PATCH] Fix visible headings sorting --- static/on-this-page.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/static/on-this-page.js b/static/on-this-page.js index 2637514073..c6d0fee4a3 100644 --- a/static/on-this-page.js +++ b/static/on-this-page.js @@ -18,13 +18,8 @@ let otp_state = new Map(); * @param {string | HTMLElement} id_or_node */ function otp_set_active(id_or_node){ - let id = ""; - if(typeof id_or_node == "object"){ - id = id_or_node.getAttribute("id"); - } else { - id = id_or_node; - } - id = "#" + id; + let id = `#${id_or_node instanceof HTMLElement ? id_or_node.getAttribute("id") : id_or_node}`; + document.querySelectorAll(".on-this-page a").forEach(a => { a.setAttribute("data-active", a.getAttribute("href") == id); }); @@ -39,10 +34,13 @@ let otp_observer = new IntersectionObserver( entries.forEach(entry => { otp_state.set(entry.target, entry.isIntersecting); }); + let intersecting = Array.from(otp_state) .filter(([_el, inter]) => inter) .map(([el, _inter]) => el); - intersecting.sort((element) => -element.getBoundingClientRect().y); + + intersecting.sort((a, b) => a.getBoundingClientRect().y - b.getBoundingClientRect().y); + if (intersecting.length > 0) { otp_set_active(intersecting[0]); }