Skip to content

Commit

Permalink
fix: synchronize scrolling the content and toc
Browse files Browse the repository at this point in the history
  • Loading branch information
deemp committed Jan 4, 2024
1 parent c915ca2 commit 250e620
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions docs/theme/pagetoc.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
var forEach = function (elems, fun) {
function forEach(elems, fun) {
Array.prototype.forEach.call(elems, fun);
};
}

// Un-active everything when you click it
var forPagetocElem = function (fun) {
function forPagetocElem(fun) {
forEach(document.getElementsByClassName("pagetoc")[0].children, fun);
};
}

forPagetocElem(function (el) {
el.addEventHandler("click", function () {
Expand All @@ -16,22 +16,42 @@ forPagetocElem(function (el) {
});
});

function getRect(element) {
return element.getBoundingClientRect();
}

function overflowTop(container, element) {
return getRect(container).top - getRect(element).top;
}

function overflowBottom(container, element) {
return getRect(container).bottom - getRect(element).bottom;
}

var updateFunction = function () {
var id;
var elements = document.getElementsByClassName("header");
forEach(elements, function (el) {
if (window.scrollY >= el.offsetTop) {
if (window.scrollY + 100 >= el.offsetTop) {
id = el;
}
});

forPagetocElem(function (el) {
el.classList.remove("active");
});

if (!id) return;
forPagetocElem(function (el) {
if (id.href.localeCompare(el.href) == 0) {
el.classList.add("active");
let pagetoc = document.getElementsByClassName("pagetoc")[0];
if (overflowTop(pagetoc, el) > 0) {
pagetoc.scrollTop = el.offsetTop;
}
if (overflowBottom(pagetoc, el) < 0) {
pagetoc.scrollTop -= overflowBottom(pagetoc, el);
}
}
});
};
Expand Down

0 comments on commit 250e620

Please sign in to comment.