AtishW
(Atish Waghwase)
June 21, 2022, 11:24am
21
Very late but this workaround is what I use for my ‘Back to top’ button -
Adding this to the URL of the link takes me to the top without changing the URL
`javascript:window.scrollTo(0, 0);
So if you add the (x, y) coordinates of the section it may work for your needs
Jesus heckin christ.
Thank you so much! How has this been so hard to find… PERFECT
gushon
(מיכאל שוורץ)
October 11, 2023, 3:38pm
23
Here’s a solition I found, an extension to @AtishW 's solution, that doesnt snap to the top but scrolls to it smoothly:
just ad an ID of #scroll-to-top
to the button, and the following code to the end of the page
<script>
document.getElementById('scroll-to-top').addEventListener('click', function(event) {
event.preventDefault();
window.scrollTo({top: 0, behavior: 'smooth'});
});
</script>
It doesn’t work for me, can someone give me a please
ddd
(DJ)
March 10, 2024, 6:04pm
25
This javascript works for me to quickly revert the URL after clicking a hash link (and also on page load):
window.addEventListener('load', () => {
window.history.replaceState('','','/',('#')[0]);
});
window.addEventListener('hashchange', () => {
window.history.replaceState('','','/',('#')[0]);
});
Credit also to stckvrw , Manjeet Kumar Nai , I combined their code and the hashchange event .
EDIT: pushState can be used instead. Supposedly pushState creates a different browser history entry while replaceState does not. I don’t see this difference, however it effects whether I can go back with the back button or not:
window.addEventListener('load', () => {
window.history.pushState('','','/',('#'),[0]);
});
window.addEventListener('hashchange', () => {
window.history.pushState('','','/',('#'),[0]);
});