Skip to content

Commit b2fe0aa

Browse files
committed
Scroll to top of page when hash fragment is #top or #
1 parent d57be48 commit b2fe0aa

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/index.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,19 @@ function reset() {
1717
}
1818

1919
function getElAndScroll() {
20-
const element = document.getElementById(hashFragment);
20+
let element = null;
21+
if (hashFragment === '#') {
22+
element = document.body;
23+
} else {
24+
// check for element with matching id before assume '#top' is the top of the document
25+
// see https://html.spec.whatwg.org/multipage/browsing-the-web.html#target-element
26+
const id = hashFragment.replace('#', '');
27+
element = document.getElementById(id);
28+
if (element === null && hashFragment === '#top') {
29+
element = document.body;
30+
}
31+
}
32+
2133
if (element !== null) {
2234
scrollFunction(element);
2335

@@ -63,13 +75,13 @@ export function genericHashLink(As) {
6375
function handleClick(e) {
6476
reset();
6577
if (props.onClick) props.onClick(e);
66-
if (typeof props.to === 'string') {
67-
hashFragment = props.to.split('#').slice(1).join('#');
78+
if (typeof props.to === 'string' && props.to.includes('#')) {
79+
hashFragment = `#${props.to.split('#').slice(1).join('#')}`;
6880
} else if (
6981
typeof props.to === 'object' &&
7082
typeof props.to.hash === 'string'
7183
) {
72-
hashFragment = props.to.hash.replace('#', '');
84+
hashFragment = props.to.hash;
7385
}
7486
if (hashFragment !== '') {
7587
scrollFunction =

0 commit comments

Comments
 (0)