xref: /plugin/combo/resources/snippet/js/menubar-fixed-top.js (revision de3bcac65378e2b05c1c328f607f5fb49d98d877)
1(function IIFE() {
2
3    /**
4     * We do the work after the first scroll
5     * to prevent a cls (layout shift)
6     * @type {boolean}
7     */
8    let done = false;
9
10    window.addEventListener("scroll", function () {
11
12        if (done) {
13            return;
14        }
15        done = true;
16
17        /**
18         * The request animation frame is there to
19         * update the class on the navbar and the padding on the
20         * body at the same time to not have any layout shift
21         */
22        window.requestAnimationFrame(function () {
23            let fixedNavbar = document.querySelector(".navbar[data-type=\"fixed-top\"]")
24            if (fixedNavbar == null) {
25                return;
26            }
27            fixedNavbar.classList.add("fixed-top")
28            // correct body padding
29            let offsetHeight = fixedNavbar.offsetHeight;
30            document.body.style.setProperty("padding-top", offsetHeight + "px");
31            // correct direct navigation via fragment to heading
32            let style = document.createElement("style");
33            style.classList.add("menubar-fixed-top")
34            // textContent and not innerText (it adds br elements)
35            style.textContent = `:target {
36  scroll-margin-top: ${offsetHeight}px;
37}`;
38            document.head.appendChild(style);
39        });
40
41    });
42})();
43