@@ -9,7 +9,7 @@ const contentDiv = document.getElementsByClassName('content')[0];
99const headings = contentDiv . querySelectorAll ( 'h1, h2, h3, h4, h5, h6' ) ;
1010let tocHTML = '' ;
1111let currentLevel = 0 ;
12- headings . forEach ( ( heading ) => {
12+ headings . forEach ( heading => {
1313 const level = parseInt ( heading . tagName [ 1 ] , 10 ) ;
1414 // Adjust indentation levels based on the heading hierarchy
1515 if ( level > currentLevel ) {
@@ -24,4 +24,29 @@ headings.forEach((heading) => {
2424} ) ;
2525tocHTML += '</li>' . repeat ( currentLevel ) ;
2626const firstDiv = document . getElementById ( 'toc-content' ) ;
27- firstDiv . insertAdjacentHTML ( 'beforeend' , tocHTML ) ;
27+ firstDiv . insertAdjacentHTML ( 'beforeend' , tocHTML ) ;
28+
29+ // Function to scroll to the heading anchor
30+ function scrollToHeadingAnchor ( ) {
31+ const hash = window . location . hash ;
32+ console . log ( 'Hash:' , hash ) ;
33+ if ( hash ) {
34+ const headings = contentDiv . querySelectorAll ( 'h1, h2, h3, h4, h5, h6' ) ;
35+ headings . forEach ( heading => {
36+ if ( toSnakeCase ( heading . innerText ) === hash . substring ( 1 ) ) {
37+ const yOffset = - 50 ; // Adjust this value if you want to offset the scroll position
38+ const y = heading . getBoundingClientRect ( ) . top + window . pageYOffset + yOffset ;
39+ console . log ( 'Scrolling to Y:' , y ) ;
40+ window . scrollTo ( { top : y , behavior : 'smooth' } ) ;
41+ }
42+ } ) ;
43+ } else {
44+ console . log ( 'No hash found in the URL.' ) ;
45+ }
46+ }
47+
48+ // Call the function on page load
49+ scrollToHeadingAnchor ( ) ;
50+
51+ // Add an event listener to scroll to the heading when the URL hash changes
52+ window . addEventListener ( 'hashchange' , scrollToHeadingAnchor ) ;
0 commit comments