Search code examples
javascripturlanchor

Remove anchor from URL and history


I have just added a back-to-top button to my blog with a simple <a href='#top'...

I face an annoying behavior that I don't see in other website's back-to-top button:

  1. The #top suffix is added to the URL - I get this one but I want to change it so it won't affect the original URL.
  2. Once I hit that button and sent back to the top of the page, a following press on the back button (alt+left) takes me to the point in the same page where I hit the back-to-top button - This is one I don't get at all. How can I prevent from this entry to get in the history?

I tried to put the code suggested here - https://stackoverflow.com/a/20198758/1692261 - in my head tag but it has 0 effect.

Edit: I add another requirement here - I want to disable the above behavior just for that button. In the future I might use anchors here and there and I would like the original behavior to take place. Is that possible or it must be block-all or allow-all?


Solution

  • the Window.scroll() method should work for you.

    https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

    the window.scroll() method does not have any effect to the url. it just tells the window, to scroll to a specific coordinate ( top: y, left: x )

    instead of using the anchor tag, add an eventListener to the button, that fires the Window.scroll()

    button.addEventListener("click", function () {
      window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
      });
    });
    

    you could calculate the exact position of your window.scroll()-target relative to the body element with this:

    const bodyRect = document.body.getBoundingClientRect(),
          elemRect = element.getBoundingClientRect(),
          offset   = elemRect.top - bodyRect.top;
    

    and than use the calculated offset for the top value in the window.scroll()

    window.scroll({
      top: offset,
      left: 0,
      behavior: 'smooth'
    });