Skip to content

Commit 7054481

Browse files
committed
Add initializer which scrolls to #user-content-X
1 parent 74a1548 commit 7054481

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

app/initializers/hashchange.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
function decodeFragmentValue(hash) {
2+
try {
3+
return decodeURIComponent(hash.slice(1));
4+
} catch (_) {
5+
return '';
6+
}
7+
}
8+
9+
function findElementByFragmentName(document, name) {
10+
if (name === '') {
11+
return;
12+
}
13+
14+
return document.getElementById(name) || document.getElementsByName(name)[0];
15+
}
16+
17+
function hashchange() {
18+
if (document.querySelector(':target')) {
19+
return;
20+
}
21+
22+
const hash = decodeFragmentValue(location.hash);
23+
const target = findElementByFragmentName(document, `user-content-${hash}`);
24+
if (target) {
25+
target.scrollIntoView();
26+
}
27+
}
28+
29+
export function initialize(application) {
30+
$(window).on('hashchange', hashchange);
31+
32+
// If clicking on a link to the same fragment as currently in the address bar,
33+
// hashchange won't be fired, so we need to manually trigger rescroll.
34+
$(document).on('a[href]', 'click', function(event) {
35+
if (this.href === location.href && location.hash.length > 1) {
36+
setTimeout(function() {
37+
if (!event.defaultPrevented) {
38+
hashchange();
39+
}
40+
});
41+
}
42+
});
43+
}
44+
45+
export default {
46+
name: 'app.hashchange',
47+
initialize
48+
};

0 commit comments

Comments
 (0)