2

I have some URI fragments in an app I'm building that will jump to elements within the page as expected, however, clicking on these fragment links also adds them to the history so if I navigate to another page and click back, it will navigate to the last page AND the fragment last used when I'd prefer to not have fragments modify the history so clicking back just takes me to the top of the previous page without auto-scrolling to the last fragment.

HaulinOats
  • 3,628
  • 4
  • 21
  • 24
  • 2
    You should let the behavior of fragments being added to the URL (history) continue as it's the behavior that people expect when using the web. There are javascript solutions to scroll to them, but this breaks user's expectations of the web. – dreadwail Apr 16 '22 at 18:38
  • You might be looking for the answer in this SO thread: https://stackoverflow.com/questions/3659072/how-to-disable-anchor-jump-when-loading-a-page – BrunoT Apr 16 '22 at 18:45
  • 1
    @HaulinOats And yet I still provided the opinion despite it not being something you asked for. Part of stackoverflow is taking into consideration the other people who will read this post besides you the asker. If the comment is not useful for you, you may ignore it. – dreadwail Apr 16 '22 at 18:51

1 Answers1

2

You may want to use the Element.scrollIntoView to scroll to an element in the document without affecting the current URL or history.

So, instead of a link like

<a href="#next-section">Scroll to next section</a>

You would have

<a href="#" onclick="document.querySelector('#next-section').scrollIntoView(); event.preventDefault();">Scroll to next section</a>

Or the equivalent code in a separate JavaScript file: basically, find the element you want to scroll to using the DOM API (with document.querySelector, document.getElementById, etc.), and then call scrollIntoView on the element.

If the element that receives the click event is a link (<a>), you will also need to call event.preventDefault() to override the default behavior of navigating to the href target (note that you may still need a dummy href attribute for the expected styling).

<a href="#" onclick="document.querySelector('#next-section').scrollIntoView(); event.preventDefault();">Scroll to next section</a>

<div style="height: 8.5em;"></div>
<h2 id="next-section">Next section</h2>
<div style="height: 7em;"></div>
<h2 id="another-section">Another section</h2>
<div style="height: 5em;"></div>
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • 1
    Shame there's not a flag you can pass with the link, or a native API to trigger, to prevent adding to history. I'm working in a React project and will ideally need to create refs for all these links in order to access them from within my click handlers but it'll work. Thanks for the detailed response. – HaulinOats Apr 18 '22 at 13:46