rstacruz / flatdoc

Build sites fast from Markdown
http://ricostacruz.com/flatdoc
2.68k stars 263 forks source link

Adding elements on('flatdoc:ready') causes scroll bar to desync #111

Open rogermiranda1000 opened 1 year ago

rogermiranda1000 commented 1 year ago

Adding elements on('flatdoc:ready') causes scroll bar to desync (it shows like you're below where you really are).

Note: The elements that I'm adding are not <h1>, <h2>...

How to reproduce

  1. Add elements on('flatdoc:ready'):
    $(document).on('flatdoc:ready', function() {
        fetch(somewhere, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
            .then(res => res.text()) // toString
            .then(html => new DOMParser().parseFromString(html, "text/html"))
            .then(element => {
                const target = document.getElementById(where_to_add);
                target.parentNode.insertBefore(element, target.nextSibling); // insert below target
            });
    }

How to solve

I've found a solution, but I don't know if it can have consequences.

  1. Once the element has been added (below the last then), add:
    .then(_ => {
        $("h2, h3").scrollagent(function(cid, pid, currentElement, previousElement) {
            if (pid) {
                $("[href='#"+pid+"']").removeClass('active');
            }
            if (cid) {
                $("[href='#"+cid+"']").addClass('active');
            }
        });
    });