How to allow the links on a RichText markdown's Table of Contents to scroll to the selected section

You can’t use hash anchor elements with hash routing. Hash routing listens for changes to the hash in the browser. And by using hash anchor elements you’re causing hash routing to fire off its routing process.

An alternative would be to and click event listeners to your links rather than hrefs

(And don’t do the history.replaceState change - that’s unnecessary with this suggestion)

from anvil.js import get_dom_node, window
from anvil.js.window import document

def scrollToHeading(event):
    document.getElementById(event.target.dataset.anchor).scrollIntoView()

def add_anchors_to_headings(rt):
    rt_node = get_dom_node(rt)
    for a in rt_node.querySelectorAll("a"):
        href = a.getAttribute("href")
        if href[0] == "#":
            a.dataset.anchor = href[1:]
            a.setAttribute("href", "javascript:void(0)")
            a.addEventListener("click", scrollToHeading)
    for h in get_dom_node(rt).querySelectorAll("h1, h2, h3"):
        h.id = h.textContent.replace(" ", "-").lower()

1 Like