tocbot icon indicating copy to clipboard operation
tocbot copied to clipboard

Update URL on scroll

Open maciejwalkowiak opened this issue 4 years ago • 1 comments

I am working on updating a URL through history.pushState when scrolling through a long document. Since this document uses already tocbot, ideally it would trigger the url change at the same time as the table of contents gets updated, so that it stays in sync.

To do it, I would have to replicate quite a bit of tocbot functionality, so I am wondering if you considered an option in tocbot to update the URL on scroll. The code for doing it is relatively simple:

function isElementInViewport (el) {
	const rect = el.getBoundingClientRect();
	return (
		rect.top >= 0 &&
		rect.left >= 0 &&
		rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
		rect.right <= (window.innerWidth || document.documentElement.clientWidth)
	);
}

const headers = document.querySelectorAll("h1,h2,h3,h4,h5");
document.addEventListener("scroll", function(e) {
	for (let el of headers) {
		if (isElementInViewport(el)) {
			if (window.history.pushState) {
				window.history.pushState(null, null, "#" + el.id);
			}
		}
	}
});

(it's just a POC code, throttling needs to be added).

If you think it makes sense, I can prepare a PR.

maciejwalkowiak avatar Apr 27 '21 17:04 maciejwalkowiak

Hey, thanks for the suggestion! I'd definitely appreciate a PR for this. :)

tscanlin avatar Apr 28 '21 23:04 tscanlin