Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Anchor Links / Hash in URL is ignored on initial page load #21120

Closed
sidyes opened this issue Feb 1, 2020 · 8 comments
Closed

Anchor Links / Hash in URL is ignored on initial page load #21120

sidyes opened this issue Feb 1, 2020 · 8 comments
Labels
type: bug An issue or pull request relating to a bug in Gatsby

Comments

@sidyes
Copy link

sidyes commented Feb 1, 2020

Description

I am having a SPA built with gatsby. I am using <a href="/#sectionX">section x</a> links for navigation in the header. This is working just fine.
Unfortunately, reloading the page (having the anchor link in the URL) does not scroll to the expected section but stays unscrolled at the top of the page.

Steps to reproduce

Take any gatsby starter, add anchor link, reload page.

Expected result

Page should automatically scroll to desired section as provided in the URL on initial page load.

Actual result

Hash is ignored and page does not scroll

Environment

System:
OS: Windows 10 10.0.17763
CPU: (8) x64 Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz
Binaries:
Node: 12.13.0 - C:\Program Files\nodejs\node.EXE
npm: 6.12.0 - C:\Program Files\nodejs\npm.CMD
Languages:
Python: 2.7.17
Browsers:
Edge: 44.17763.831.0

@danspratling
Copy link
Contributor

Looks like gatsby takes control of the scroll position but you can use the gatsby-browser.js file to add a function to re-enable anchor links.

exports.onRouteUpdate = ({ location }) => scrollToAnchor(location)

/**
 *
 * @desc - a function to jump to the correct scroll position
 * @param {Object} location -
 * @param {Number} [mainNavHeight] - the height of any persistent nav -> document.querySelector(`nav`)
 */
function scrollToAnchor(location, mainNavHeight = 0) {
  // Check for location so build does not fail
  if (location && location.hash) {
    const item = document.querySelector(`${location.hash}`).offsetTop

    window.scrollTo({
      top: item - mainNavHeight,
      behavior: "smooth",
    })
  }

  return true
}

I'm not sure if the default browser behaviour for anchor links being disabled is intentional or not though. Would be worth getting some feedback from someone on the internal team.

@sidyes
Copy link
Author

sidyes commented Feb 2, 2020

@danspratling:
Thank you! It is working now - but as you said it would be really interesting what the intention of this really is from someone official.

I let this thread open for now to get hopefully an anweser.

@danspratling danspratling added the type: question or discussion Issue discussing or asking a question about Gatsby label Feb 4, 2020
@github-actions
Copy link

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 30 days of inactivity. It’s been at least 20 days since the last update here.
If we missed this issue or if you want to keep it open, please reply here. You can also add the label "not stale" to keep this issue open!
As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

@github-actions github-actions bot added the stale? Issue that may be closed soon due to the original author not responding any more. label Feb 25, 2020
@danspratling danspratling added not stale and removed stale? Issue that may be closed soon due to the original author not responding any more. labels Feb 26, 2020
@admackin
Copy link

Yep this has bitten me too!

@karlhorky
Copy link
Contributor

karlhorky commented May 19, 2020

@danspratling you'll want to also update the scrollToAnchor function with the following, to fix ids starting with numbers, which results in an error like SyntaxError: Failed to execute 'querySelector' on 'Document': '...' is not a valid selector.:

// Fix scrolling for ids starting with numbers
// https://stackoverflow.com/a/20306237/1268612
const hash = location.hash.replace(/^#(\d)/, '#\\3$1');

@LekoArts LekoArts added type: bug An issue or pull request relating to a bug in Gatsby and removed type: question or discussion Issue discussing or asking a question about Gatsby labels May 26, 2020
@blainekasten
Copy link
Contributor

Fixed in latest!

winsvold added a commit to navikt/dp-faktasider-frontend that referenced this issue Jul 2, 2020
…ker da det ga litt rar oppførsel og ikke er anbefalt av gatsby

måtte implementere litt custom greier da dette ikke ser ut til å virke ut av boksen med gatsby
gatsbyjs/gatsby#21120
https://codingcat.dev/blog/anchor-links-from-sanity-in-gatsby/#sanityio
https://stackoverflow.com/questions/24665602/scrollintoview-scrolls-just-too-far

trodde egentlig denne PR'en skulle fikse det, men ser ikke at det funker..?
gatsbyjs/gatsby#24306
@LekoArts LekoArts removed the not stale label Jul 3, 2020
@dmaxchristiansen
Copy link

It looks like this issue is presenting itself again in Gatsby v5

@sykoivisto
Copy link

Still showing this issue in 5.8.1

danspratling's fix is still working

Looks like gatsby takes control of the scroll position but you can use the gatsby-browser.js file to add a function to re-enable anchor links.

exports.onRouteUpdate = ({ location }) => scrollToAnchor(location)

/**
 *
 * @desc - a function to jump to the correct scroll position
 * @param {Object} location -
 * @param {Number} [mainNavHeight] - the height of any persistent nav -> document.querySelector(`nav`)
 */
function scrollToAnchor(location, mainNavHeight = 0) {
  // Check for location so build does not fail
  if (location && location.hash) {
    const item = document.querySelector(`${location.hash}`).offsetTop

    window.scrollTo({
      top: item - mainNavHeight,
      behavior: "smooth",
    })
  }

  return true
}

I'm not sure if the default browser behaviour for anchor links being disabled is intentional or not though. Would be worth getting some feedback from someone on the internal team.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: bug An issue or pull request relating to a bug in Gatsby
Projects
None yet
Development

No branches or pull requests

9 participants