If you want the state to persist between reloads, then you'll need to use the
Web Storage API[
^] to save your state as it changes, and reload it when the page loads.
For example, add a unique ID to each link and section toggle, and store the ID of the clicked link and the IDs of the expanded sections.
const stateKey = "TOC-State";
const state = {
selectedLink: null,
expandedLinks: []
};
function loadState() {
const json = window.sessionStorage.getItem(stateKey);
return json ? JSON.parse(json) : null;
}
function saveState() {
window.sessionStorage.setItem(stateKey, JSON.stringify(state));
}
function setSelectedLink(linkId) {
document.querySelectorAll(".tlink.active").forEach(l => l.classList.remove("active"));
document.getElementById(linkId)?.classList.add("active");
}
function toggleLink(linkId, expand) {
const tlink = document.getElementById(linkId);
if (!tlink) { return; }
tlink.classList.toggle("expanded", expand);
tlink.nextElementSibling.classList.toggle("show", expand);
}
document.addEventListener("DOMContentLoaded", () => {
const savedState = loadState();
if (savedState) {
state = savedState;
if (state.selectedLink) { setSelectedLink(state.selectedLink); }
if (state.expandedLinks) { state.expandedLinks.forEach(id => toggleLink(id, true)); }
} else {
state.selectedLink = document.querySelector(".reference.selected")?.id;
state.expandedLinks = [...document.querySelectorAll(".tlink.expanded")].map(l => l.id);
}
});
document.addEventListener("click", ({ target }) => {
if (target.tagName !== "A") { target = target.closest("a"); }
if (!target || !target.classList.contains("reference")) { return; }
setSelectedLink(target.id);
state.selectedLink = target.id;
saveState();
});
document.addEventListener("click", ({ target }) => {
if (target.tagName !== "DIV" || !target.classList.contains("tlink")) { target = target.closest("div.tlink"); }
if (!target) { return; }
const id = target.id;
const index = state.expandedLinks.indexOf(id);
if (target.classList.contains("expanded")) {
if (index !== -1) { state.expandedLinks.splice(index, 1); }
toggleLink(id, false);
} else {
if (index === -1) { state.expandedLinks.push(id); }
toggleLink(id, true);
}
});