Same-page links

  • Partial workaround for issue Best way to add internal link?
  • Add the following code into file custom.js:
    const raws = document.getElementsByClassName("raw_html");
    const anchorObserver = new MutationObserver(function onMutated(){
        Array.prototype.forEach.call(raws, (raw)=>{
            Array.prototype.forEach.call(raw.querySelectorAll("a[href]"), (anchor)=>{
                const href = anchor.getAttribute("href")
                if (!href?.startsWith("#")) return
                if (anchor.dataset.status === "fixed") return
      
                anchor.addEventListener("click", (e)=>{
                    e.preventDefault()
                    const target = document.querySelector('[id="' + href.slice(1) + '"]')
                    if (target) target.scrollIntoView()
                })
                anchor.dataset.status = "fixed"
            })
        })
    });
    anchorObserver.observe(document.getElementById("app-container"), {
        attributes: true,
        subtree: true,
        attributeFilter: ["class"]
    });
    
  • Works only if the target element has been loaded.
    • In other words, if clicking does nothing:
      • scroll to the end of the page
        • e.g. pressing End multiple times
      • then return to the link and click again

Thank you for this option. I have been watching the thread related to this, and I am looking for exactly that functionality:

Has anyone had success in using the method suggested here in this newer thread? I am about to try it and will report back too.

Edit: I was hoping to use a set of links on my sidebar to control movement within a page located within the main screen. Is that possible?

thanks!

So far this is not working for me. I created a set of block references that referred to blocks further down the same page. When I click on those block references, it brings up the block, but it does not scroll to the specified location on the same page.

Am I doing something wrong, or not using this as intended. I did make sure that i scrolled first to the end of the page to be sure the full page was loaded.

This is not about Logseq block references, but about HTML anchor links. From the related thread, you are supposed to use this type of HTML (i.e. id and a/href/#), directly into your markdown:

<a href="#another-mark">anchor</a>
<h2 id="another-mark">link to anchor</h2>
1 Like