@@ -40,14 +40,22 @@ class MDBookSidebarScrollbox extends HTMLElement {
4040 // Track and set sidebar scroll position
4141 this . addEventListener ( 'click' , e => {
4242 if ( e . target . tagName === 'A' ) {
43- sessionStorage . setItem ( 'sidebar-scroll' , this . scrollTop ) ;
43+ const clientRect = e . target . getBoundingClientRect ( ) ;
44+ const sidebarRect = this . getBoundingClientRect ( ) ;
45+ sessionStorage . setItem ( 'sidebar-scroll-offset' , clientRect . top - sidebarRect . top ) ;
4446 }
4547 } , { passive : true } ) ;
46- const sidebarScrollTop = sessionStorage . getItem ( 'sidebar-scroll' ) ;
47- sessionStorage . removeItem ( 'sidebar-scroll' ) ;
48- if ( sidebarScrollTop ) {
48+ const sidebarScrollOffset = sessionStorage . getItem ( 'sidebar-scroll-offset ' ) ;
49+ sessionStorage . removeItem ( 'sidebar-scroll-offset ' ) ;
50+ if ( sidebarScrollOffset !== null ) {
4951 // preserve sidebar scroll position when navigating via links within sidebar
50- this . scrollTop = sidebarScrollTop ;
52+ const activeSection = this . querySelector ( '.active' ) ;
53+ if ( activeSection ) {
54+ const clientRect = activeSection . getBoundingClientRect ( ) ;
55+ const sidebarRect = this . getBoundingClientRect ( ) ;
56+ const currentOffset = clientRect . top - sidebarRect . top ;
57+ this . scrollTop += currentOffset - parseFloat ( sidebarScrollOffset ) ;
58+ }
5159 } else {
5260 // scroll sidebar to current active section when navigating via
5361 // 'next/previous chapter' buttons
0 commit comments