Skip to content

Commit 258d956

Browse files
Re-clicking the link icon removes the hash
Fixes #158
1 parent a965e4c commit 258d956

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

src/components/Linkable/Header.tsx

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,32 @@ export function smoothScrollHash(
88
e.preventDefault();
99
const href = e.currentTarget.href;
1010
setTimeout(() => {
11-
const hash = href.split("#")[1];
12-
console.log(`Smooth scrolling to ${hash}`);
13-
smoothScrollToID(hash);
14-
window.dispatchEvent(new HashChangeEvent("hashchange", { newURL: href }));
11+
const newHash = href.split("#")[1];
12+
console.log(`Smooth scrolling to ${newHash}`);
13+
smoothScrollToID(newHash);
1514
});
1615
}
1716

1817
export function smoothScrollToID(id: string) {
1918
const u = new URL(window.location.toString());
19+
if (u.hash === `#${id}`) {
20+
console.log("Already scrolled to hash, removing it");
21+
id = "";
22+
}
2023
u.hash = id;
2124
setTimeout(() => {
2225
window.history.replaceState({}, "", u.toString());
2326
});
24-
const e = document.getElementById(id);
25-
e?.scrollIntoView({
26-
behavior: "smooth",
27-
block: "center",
28-
});
27+
if (id.length > 0) {
28+
const e = document.getElementById(id);
29+
e?.scrollIntoView({
30+
behavior: "smooth",
31+
block: "center",
32+
});
33+
}
34+
window.dispatchEvent(
35+
new HashChangeEvent("hashchange", { newURL: u.toString() }),
36+
);
2937
}
3038

3139
export function LinkableH2({

0 commit comments

Comments
 (0)