Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update URL on scroll #229

Open
maciejwalkowiak opened this issue Apr 27, 2021 · 1 comment
Open

Update URL on scroll #229

maciejwalkowiak opened this issue Apr 27, 2021 · 1 comment

Comments

@maciejwalkowiak
Copy link

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.

@tscanlin
Copy link
Owner

tscanlin commented Apr 28, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants