diff --git a/content/2025-10-11-pelican-theme-upgrade-right-sidebar-toc.rst b/content/2025-10-11-pelican-theme-upgrade-right-sidebar-toc.rst index 735418d..825c18e 100644 --- a/content/2025-10-11-pelican-theme-upgrade-right-sidebar-toc.rst +++ b/content/2025-10-11-pelican-theme-upgrade-right-sidebar-toc.rst @@ -312,4 +312,33 @@ The theme toggle function switches between them by enabling/disabling the styles The flash-of-unstyled-content prevention script also switches the syntax highlighting stylesheet before the page renders, ensuring code blocks always appear with the correct colors. +**Preventing Scroll Jump with URL Anchors** + +When toggling themes on a page with a URL anchor (like ``#syntax-highlighting-theme-switching``), the browser would jump to the anchor after theme changes caused layout reflow. This creates poor UX when users toggle themes mid-article. + +The solution temporarily removes the hash from the URL during theme toggle, then restores it without triggering navigation: + +.. code-block:: javascript + + function toggleTheme() { + // Save current scroll position and hash + const scrollY = window.scrollY; + const hash = window.location.hash; + + // Temporarily remove hash to prevent jump + if (hash) { + history.replaceState(null, null, ' '); + } + + // ... perform theme toggle ... + + // Restore scroll position and hash without jumping + window.scrollTo(0, scrollY); + if (hash) { + history.replaceState(null, null, hash); + } + } + +This preserves both the scroll position and the URL anchor without triggering the browser's default anchor-jumping behavior. + .. contents::