Skip to content

Commit

Permalink
fix(gatsby-remark-autolink-headers): Scroll to document top (#20363)
Browse files Browse the repository at this point in the history
* Fixed scroll position for autolink-headers

Fixed scroll position issues with relative parent for gatsby-remark-autolink-headers gatsby-browser.js

* fixed scroll for autolink headers in gatsby-ssr

Fixed scroll position issues with relative parent for gatsby-remark-autolink-headers in gatsby-ssr.js

* chore: format

Co-authored-by: GatsbyJS Bot <mathews.kyle+gatsbybot@gmail.com>
  • Loading branch information
Rikpat and GatsbyJS Bot committed Jan 9, 2020
1 parent a4e5fb9 commit 1810254
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
10 changes: 9 additions & 1 deletion packages/gatsby-remark-autolink-headers/src/gatsby-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ const getTargetOffset = hash => {
if (id !== ``) {
const element = document.getElementById(id)
if (element) {
return element.offsetTop - offsetY
let scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop
let clientTop =
document.documentElement.clientTop || document.body.clientTop || 0
return (
element.getBoundingClientRect().top + scrollTop - clientTop - offsetY
)
}
}
return null
Expand Down
4 changes: 3 additions & 1 deletion packages/gatsby-remark-autolink-headers/src/gatsby-ssr.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
if (hash !== '') {
var element = document.getElementById(hash)
if (element) {
var offset = element.offsetTop
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
let clientTop = document.documentElement.clientTop || document.body.clientTop || 0
var offset = element.getBoundingClientRect().top + scrollTop - clientTop
// Wait for the browser to finish rendering before scrolling.
setTimeout((function() {
window.scrollTo(0, offset - ${offsetY})
Expand Down

0 comments on commit 1810254

Please sign in to comment.