makes toc scroll plays well with InstantClick

by adding/removing scroll event listener each time page is loaded
This commit is contained in:
Reorx 2022-04-13 00:28:44 +08:00
parent d4b3ef754f
commit 1019c47b7c
1 changed files with 23 additions and 7 deletions

View File

@ -138,12 +138,26 @@
</script> </script>
{{- end }} {{- end }}
{{- if (and (eq .Kind "page") (.Content) (.Param "ShowToc") (.Param "TocSide")) }}
<script> <script>
window.addEventListener('DOMContentLoaded', function (event) { // NOTE use closure instead of DOMContentLoaded because of InstantClick,
if (!document.querySelector('.toc')) { // every page loaded by InstantClick should run the <script> tags again.
return; (function() {
const enableTocScroll = '{{- if (and (eq .Kind "page") (.Content) (.Param "ShowToc") (.Param "TocSide")) }}1{{ end }}' == '1'
let scrollListeners = window.scrollListeners
if (scrollListeners === undefined) {
scrollListeners = []
window.scrollListeners = scrollListeners
} }
if (!enableTocScroll || !document.querySelector('.toc')) {
// console.log('disable toc scroll', scrollListeners)
for (const listener of scrollListeners) {
window.removeEventListener('scroll', listener)
}
return
}
const headings = document.querySelectorAll('h1[id],h2[id],h3[id],h4[id],h5[id]'); const headings = document.querySelectorAll('h1[id],h2[id],h3[id],h4[id],h5[id]');
const activeClass = 'active'; const activeClass = 'active';
@ -174,12 +188,14 @@ window.addEventListener('DOMContentLoaded', function (event) {
} }
let timer = null; let timer = null;
window.addEventListener('scroll', () => { const scrollListener = () => {
if (timer !== null) { if (timer !== null) {
clearTimeout(timer) clearTimeout(timer)
} }
timer = setTimeout(onScroll, 50) timer = setTimeout(onScroll, 50)
}, false); }
window.addEventListener('scroll', scrollListener, false);
scrollListeners.push(scrollListener)
function getLinkByHeading(heading) { function getLinkByHeading(heading) {
const id = encodeURI(heading.getAttribute('id')).toLowerCase(); const id = encodeURI(heading.getAttribute('id')).toLowerCase();
@ -193,7 +209,7 @@ window.addEventListener('DOMContentLoaded', function (event) {
let rect = heading.getBoundingClientRect(); let rect = heading.getBoundingClientRect();
return rect.top return rect.top
} }
}, false); })();
</script> </script>
{{- end }} {{- end }}