Skip to content

Commit e18113a

Browse files
authored
Merge pull request #2104 from zqianem/gh-443/sidebar-scroll
Fix flicker when setting sidebar scroll position
2 parents d4edbd1 + 72b3227 commit e18113a

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

src/theme/book.js

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -551,13 +551,6 @@ function playground_text(playground, hidden = true) {
551551
firstContact = null;
552552
}
553553
}, { passive: true });
554-
555-
// Scroll sidebar to current active section
556-
var activeSection = document.getElementById("sidebar").querySelector(".active");
557-
if (activeSection) {
558-
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
559-
activeSection.scrollIntoView({ block: 'center' });
560-
}
561554
})();
562555

563556
(function chapterNavigation() {

src/theme/index.hbs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,28 @@
110110
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
111111
</nav>
112112

113+
<!-- Track and set sidebar scroll position -->
114+
<script>
115+
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
116+
sidebarScrollbox.addEventListener('click', function(e) {
117+
if (e.target.tagName === 'A') {
118+
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
119+
}
120+
}, { passive: true });
121+
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
122+
sessionStorage.removeItem('sidebar-scroll');
123+
if (sidebarScrollTop) {
124+
// preserve sidebar scroll position when navigating via links within sidebar
125+
sidebarScrollbox.scrollTop = sidebarScrollTop;
126+
} else {
127+
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
128+
var activeSection = document.querySelector('#sidebar .active');
129+
if (activeSection) {
130+
activeSection.scrollIntoView({ block: 'center' });
131+
}
132+
}
133+
</script>
134+
113135
<div id="page-wrapper" class="page-wrapper">
114136

115137
<div class="page">

0 commit comments

Comments
 (0)