1

I am trying to create an effect in an HTML page whereby a link with href='#section1' when clicked, changes the URL in the address bar of the browser AND scrolls to the element #section1 smoothly.

The problem is that, as far as I have been able to test, I could accomplish only one thing. Either I could scroll to #section1 smoothly using the scrollIntoView() method or I could change the address bar of the browser (which happens automatically when a link with href='#section1' is clicked.

Is there any way to accomplish both of these things?

Another thing I have tested is explained as follows:

I prevented the default action of clicking the anchor having href='#section1' using e.preventDefault() method of the click event and then called scrollIntoView() on the element. Then I manually changed the URL on the address bar using location.hash, but doing this last thing nonetheless caused the snappy scroll jump (before the browser could smoothly scroll the element into view) which I don't want.

Is there any solution to this? Or that I have to go with only one thing out of the two?

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • [This question](https://stackoverflow.com/questions/67109682/eventlistener-apply-to-previous-line/67109836#67109836) is very similar. It uses `requestAnimationFrame()` to apply the event listener. Also, it would help if you posted a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Rojo Apr 18 '21 at 14:13
  • Check this out for few possible solutions [Prevent hash change from scrolling](https://stackoverflow.com/a/21173690/4595934) – Ravikumar Apr 18 '21 at 15:20

0 Answers0