Skip to content

Commit

Permalink
Javascript: improve scrolling ToC to active entry (PR #2158)
Browse files Browse the repository at this point in the history
  • Loading branch information
ascholerChemeketa authored and rbeezer committed May 9, 2024
1 parent 6961382 commit bdb7727
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions js/pretext.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,31 @@
*/

function scrollTocToActive() {
pagefilename = window.location.href;
pagefilename = pagefilename.match(/[^\/]*$/)[0];
possibletocentries = document.querySelectorAll('#ptx-toc a[href="' + pagefilename + '"]');
if (possibletocentries.length == 0) {
console.log("linked below a subsection");
pagefilename = pagefilename.match(/^[^\#]*/)[0];
possibletocentries = document.querySelectorAll('#ptx-toc a[href="' + pagefilename + '"]');
//Try to figure out current TocItem from URL
let fileNameWHash = window.location.href.split("/").pop();
let fileName = fileNameWHash.split("#")[0];

//Find just the filename in ToC
let tocEntry = document.querySelector('#ptx-toc a[href="' + fileName + '"]');
if (!tocEntry) {
return; //complete failure, get out
}
if (possibletocentries.length == 0) {
console.log("error, cannot find", pagefilename, "in TOC");
return

//See if we can also match fileName#hash
let tocEntryWHash = document.querySelector(
'#ptx-toc a[href="' + fileNameWHash + '"]'
);
if (tocEntryWHash) {
//Matched something below a subsection - activate the list item that contains it
tocEntryWHash.closest("li").classList.add("active");
}
possibletocentries[0].scrollIntoView({block: "center"});
possibletocentries[0].classList.add("active");}

//Now activate ToC item for fileName and scroll to it
// Don't use scrollIntoView because it changes users tab position in Chrome
// and messes up keyboard navigation
tocEntry.closest("li").classList.add("active");
document.querySelector("#ptx-toc").scrollTop = tocEntry.offsetTop;
}

function toggletoc() {
thesidebar = document.getElementById("ptx-sidebar");
Expand Down

0 comments on commit bdb7727

Please sign in to comment.