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?