Skip to content

Commit

Permalink
feat: scroll page to target heading when event hashchange has been …
Browse files Browse the repository at this point in the history
…triggered
  • Loading branch information
子奂 committed Jan 14, 2020
1 parent 476f0e5 commit e76941d
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export class MarkdownNavbar extends Component {
this.addTargetTimeout = setTimeout(() => {
this.initHeadingsId();
document.addEventListener('scroll', this.winScroll, false);
window.addEventListener('hashchange', this.winHashChange, false);
}, 500);
}

Expand Down Expand Up @@ -71,6 +72,7 @@ export class MarkdownNavbar extends Component {
clearTimeout(this.scrollTimeout);
}
document.removeEventListener('scroll', this.winScroll, false);
window.removeEventListener('hashchange', this.winHashChange, false);
}

getNavStructure() {
Expand Down Expand Up @@ -143,7 +145,9 @@ export class MarkdownNavbar extends Component {

this.scrollTimeout = setTimeout(() => {
const target = document.querySelector(`[data-id="${dataId}"]`);
window.scrollTo(0, target.offsetTop - this.props.headingTopOffset);
if (target && typeof target.offsetTop === 'number') {
window.scrollTo(0, target.offsetTop - this.props.headingTopOffset);
}
}, 0);
}

Expand Down Expand Up @@ -236,6 +240,10 @@ export class MarkdownNavbar extends Component {
});
};

winHashChange = () => {
this.scrollToTarget(this.getCurrentHashValue());
};

updateHash(value) {
window.history.replaceState(
{},
Expand Down

0 comments on commit e76941d

Please sign in to comment.