Document scroll jump prevention solution for URL anchors
This commit is contained in:
parent
5f3d4e988a
commit
250a06a032
1 changed files with 29 additions and 0 deletions
|
|
@ -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.
|
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::
|
.. contents::
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue