@@ -394,19 +394,28 @@ class Theme {
394394 }
395395
396396 initRelated ( ) {
397+ // Clean up any listeners from the previous page to prevent conflicts.
398+ if ( this . _relatedOnScroll ) {
399+ this . scrollEventSet . delete ( this . _relatedOnScroll ) ;
400+ this . resizeEventSet . delete ( this . _relatedOnScroll ) ;
401+ }
402+
397403 const $relatedAuto = document . getElementById ( 'related-auto' ) ;
398404 if ( ! $relatedAuto ) return ;
399405
400406 const $relatedContentStatic = document . getElementById ( 'related-content-static' ) ;
401407 if ( $relatedContentStatic ) {
402- $relatedAuto . querySelector ( '.related-content' ) . appendChild ( $relatedContentStatic ) ;
408+ const $relatedContentAuto = $relatedAuto . querySelector ( '.related-content' ) ;
409+ if ( $relatedContentAuto ) {
410+ $relatedContentAuto . appendChild ( $relatedContentStatic ) ;
411+ }
403412 }
404413
405414 const $toc = document . getElementById ( 'toc-auto' ) ;
406415 if ( ! $toc ) return ;
407416
408- // This function ONLY handles vertical scrolling adjustments .
409- this . _relatedOnScroll = this . _relatedOnScroll || ( ( ) => {
417+ // Create a new scroll handler function for the current page .
418+ this . _relatedOnScroll = ( ) => {
410419 // If the panel's container is hidden by CSS, do nothing.
411420 if ( getComputedStyle ( $relatedAuto . parentElement ) . display === 'none' ) {
412421 return ;
@@ -416,15 +425,13 @@ class Theme {
416425 const headerHeight = document . getElementById ( 'header-desktop' ) . offsetHeight ;
417426 const TOP_SPACING = 20 + ( headerIsFixed ? headerHeight : 0 ) ;
418427
419- // Use the TOC's position as the reliable source of truth for vertical alignment.
420428 const minRelatedTop = $toc . offsetTop ;
421429 const minScrollTop = minRelatedTop - TOP_SPACING ;
422430
423431 const footerTop = document . getElementById ( 'post-footer' ) . offsetTop ;
424432 const maxRelatedTop = footerTop - $relatedAuto . getBoundingClientRect ( ) . height ;
425433 const maxScrollTop = maxRelatedTop - TOP_SPACING ;
426434
427- // Set initial position before scrolling begins
428435 if ( $relatedAuto . style . position !== 'fixed' ) {
429436 $relatedAuto . style . position = 'absolute' ;
430437 $relatedAuto . style . top = `${ minRelatedTop } px` ;
@@ -440,12 +447,11 @@ class Theme {
440447 $relatedAuto . style . position = 'fixed' ;
441448 $relatedAuto . style . top = `${ TOP_SPACING } px` ;
442449 }
443- } ) ;
450+ } ;
444451
445- // Run once on load and add to the scroll listener .
452+ // Run once on load and add the new handler to the event listeners .
446453 this . _relatedOnScroll ( ) ;
447454 this . scrollEventSet . add ( this . _relatedOnScroll ) ;
448- // Also run on resize to catch layout shifts.
449455 this . resizeEventSet . add ( this . _relatedOnScroll ) ;
450456 }
451457
0 commit comments