Skip to content

Commit 5f38acd

Browse files
silverwindlunnyzeripath
authored
Fix markdown anchor re-clicking (go-gitea#21931)
The hashchange event did not fire on re-click of a active anchor. Instead, use the click event which always fires. Fixes: go-gitea#21680 Co-authored-by: Lunny Xiao <[email protected]> Co-authored-by: zeripath <[email protected]>
1 parent d7f12af commit 5f38acd

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

web_src/js/markup/anchors.js

+9-6
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@ import {svg} from '../svg.js';
22

33
const headingSelector = '.markup h1, .markup h2, .markup h3, .markup h4, .markup h5, .markup h6';
44

5-
function scrollToAnchor() {
6-
if (document.querySelector(':target')) return;
7-
if (!window.location.hash || window.location.hash.length <= 1) return;
8-
const id = decodeURIComponent(window.location.hash.substring(1));
5+
function scrollToAnchor(hash, initial) {
6+
// abort if the browser has already scrolled to another anchor during page load
7+
if (initial && document.querySelector(':target')) return;
8+
if (hash?.length <= 1) return;
9+
const id = decodeURIComponent(hash.substring(1));
910
const el = document.getElementById(`user-content-${id}`);
1011
if (el) {
1112
el.scrollIntoView();
@@ -24,9 +25,11 @@ export function initMarkupAnchors() {
2425
a.classList.add('anchor');
2526
a.setAttribute('href', `#${encodeURIComponent(originalId)}`);
2627
a.innerHTML = svg('octicon-link');
28+
a.addEventListener('click', (e) => {
29+
scrollToAnchor(e.currentTarget.getAttribute('href'), false);
30+
});
2731
heading.prepend(a);
2832
}
2933

30-
scrollToAnchor();
31-
window.addEventListener('hashchange', scrollToAnchor);
34+
scrollToAnchor(window.location.hash, true);
3235
}

0 commit comments

Comments
 (0)