@@ -195,6 +195,7 @@ function generateToc() {
195195 link . setAttribute ( 'data-target' , heading . id ) ;
196196
197197 li . appendChild ( link ) ;
198+ setHeadingScrollHandler ( heading , link ) ;
198199 tocList . appendChild ( li ) ;
199200 } ) ;
200201
@@ -271,21 +272,30 @@ function hookTocActiveHighlighting() {
271272 targetHeadings . forEach ( ( heading ) => {
272273 observer . observe ( heading ) ;
273274 } ) ;
275+ }
274276
275- // Smooth scroll when clicking TOC links
276- tocLinks . forEach ( ( link ) => {
277- link . addEventListener ( 'click' , ( e ) => {
278- e . preventDefault ( ) ;
279- const targetId = link . getAttribute ( 'data-target' ) ;
280- const targetHeading = document . getElementById ( targetId ) ;
281- if ( targetHeading ) {
282- targetHeading . scrollIntoView ( { behavior : 'smooth' , block : 'start' } ) ;
283- history . pushState ( null , '' , `#${ targetId } ` ) ;
284- }
285- } ) ;
277+ function setHeadingScrollHandler ( heading , link ) {
278+ // Smooth scroll to heading when clicking link
279+ if ( ! heading . id ) return ;
280+
281+ link . addEventListener ( 'click' , ( e ) => {
282+ e . preventDefault ( ) ;
283+ heading . scrollIntoView ( { behavior : 'smooth' , block : 'start' } ) ;
284+ history . pushState ( null , '' , `#${ heading . id } ` ) ;
286285 } ) ;
287286}
288287
288+ function setHeadingSelfLinkScrollHandlers ( ) {
289+ // Clicking link inside heading scrolls smoothly to heading itself
290+ const headings = document . querySelectorAll ( 'h1, h2, h3, h4, h5, h6' ) ;
291+ headings . forEach ( ( heading ) => {
292+ if ( ! heading . id ) return ;
293+
294+ const link = heading . querySelector ( `a[href^="#${ heading . id } "]` ) ;
295+ if ( link ) setHeadingScrollHandler ( heading , link ) ;
296+ } )
297+ }
298+
289299/* ===== Mobile Search Modal ===== */
290300
291301function hookSearchModal ( ) {
@@ -466,6 +476,7 @@ document.addEventListener('DOMContentLoaded', () => {
466476 hookFocus ( ) ;
467477 hookSidebar ( ) ;
468478 generateToc ( ) ;
479+ setHeadingSelfLinkScrollHandlers ( ) ;
469480 hookTocActiveHighlighting ( ) ;
470481 hookSearchModal ( ) ;
471482 wrapCodeBlocksWithCopyButton ( ) ;
0 commit comments