Is there a way to scroll to URI fragments without adding them to history?

1.2k views Asked by At

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.

1

There are 1 answers

1
GOTO 0 On BEST ANSWER

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>