Skip to content

Commit 4dcb787

Browse files
committed
fix hash navigation and scroll position
1 parent 85935f7 commit 4dcb787

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

pages/scripts/clipboard.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ for (const permalinkEl of document.querySelectorAll('.permalink')) {
1414
function handleClicks(e) {
1515
// No need to scroll
1616
e.preventDefault();
17-
// Add hash back to url
18-
history.pushState({}, '', href);
17+
// Add hash back to url, but without pushState cuz it usually creates more problems
18+
window.location.href = href;
1919

2020
const textBlob = new Blob([e.type === 'dblclick' ? markdown : href], { type: 'text/plain' });
2121
const htmlBlob = new Blob([htmlStr], { type: 'text/html' });
@@ -44,5 +44,16 @@ for (const permalinkEl of document.querySelectorAll('.permalink')) {
4444
// This can happen if the user denies clipboard permissions
4545
.catch(err => console.error('Could not copy to clipboard: ', err));
4646
}
47-
4847
};
48+
49+
// Handle back-button navigations through hashes. (yes it does seem weird that this need to be done manually.......)
50+
window.addEventListener("popstate", scrollToCurrentHash);
51+
document.addEventListener("DOMContentLoaded", scrollToCurrentHash);
52+
function scrollToCurrentHash(e) {
53+
const u = new URL(location.href);
54+
const hash = u.hash.slice(1);
55+
if (!hash) return;
56+
57+
const elem = document.querySelector(`#${hash}`);
58+
elem.scrollIntoView({block: 'start'});
59+
}

0 commit comments

Comments
 (0)