1

I am a JavaScript rookie. Using a free template code for building a web page. I have a perfectly working back to top snippet but the problem is, it is adding "#" to the URL when i click on it. And when i click browser back button i had to click twice as it is removing the hash on first click and then click again to go to previous page, which is pretty annoying. Though there are tons of jQuery examples to achieve this i don't want to add jQuery and use just the JavaScript i have. Here is the code. Is there any way to remove "#" from the URL when i click the scroll to top anchor?. I tried changing the anchor tag to button as well but i could not manage to get it work. Pleas help.

HTML

<a href="#" class="back-to-top"><i class="bi bi-arrow-up-short"></i></a> 

JS

(function () {
    /**
       * Easy selector helper function
       */
      const select = (el, all = false) => {
        el = el.trim()
        if (all) {
          return [...document.querySelectorAll(el)]
        } else {
          return document.querySelector(el)
        }
      }
    
      /**
       * Easy event listener function
       */
      const on = (type, el, listener, all = false) => {
        let selectEl = select(el, all)
        if (selectEl) {
          if (all) {
            selectEl.forEach(e => e.addEventListener(type, listener))
          } else {
            selectEl.addEventListener(type, listener)
          }
        }
      }
    
      /**
       * Easy on scroll event listener 
       */
      const onscroll = (el, listener) => {
        el.addEventListener('scroll', listener)
      }
           
    
      /**
       * Back to top button
       */
      let backtotop = select('.back-to-top')
      if (backtotop) {
        const toggleBacktotop = () => {
          if (window.scrollY > 100) {
            backtotop.classList.add('active')
          } else {
            backtotop.classList.remove('active')
          }
        }
        window.addEventListener('load', toggleBacktotop)
        onscroll(document, toggleBacktotop)
      }
})();
Anil kumar
  • 45
  • 5
  • 1
    Does this answer your question? [How to prevent default event handling in an onclick method?](https://stackoverflow.com/questions/7056669/how-to-prevent-default-event-handling-in-an-onclick-method) – evolutionxbox Oct 20 '21 at 09:23
  • you can try this code https://stackoverflow.com/a/55926067/7162602 – Arman H Oct 20 '21 at 09:24
  • Might this help? https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo – insyri Oct 20 '21 at 09:25
  • @ evolutionxbox too good for me to understand it as said I am a rookie. – Anil kumar Oct 20 '21 at 10:05
  • Arman and insyri both of your js may work but not without fiddling my show hide visibility of the anchor. Thanks for the answers though – Anil kumar Oct 20 '21 at 10:06

6 Answers6

3

To prevent the # being added to the url you can use preventDefault to prevent the default anchor link behaviour:

document.querySelector('a').addEventListener('click', (event) => {
  event.preventDefault();
  window.scrollTo(0, 0);
});
.spacer {
  width: 100%;
  height: 150vh;
  border: 1px dashed black;
}
<div class="spacer"></div>


<a href="#">Back to Top</a>

or use window.scroll for native smooth scrolling behaviour (but be wary of the browser support)

document.querySelector('a').addEventListener('click', (event) => {
  event.preventDefault();
  window.scroll({
    top: 0,
    behavior: 'smooth'
  });
});
.spacer {
  width: 100%;
  height: 150vh;
  border: 1px dashed black;
}
<div class="spacer"></div>


<a href="#">Back to Top</a>
D-Money
  • 2,375
  • 13
  • 27
  • 1
    FYI: Smooth scroll can also be added via CSS: `html:focus-within { scroll-behavior: smooth; }` – Reyno Oct 20 '21 at 09:33
0

Does this answer to your question ?

Make an onClick function with this sample:

window.scrollTo(0, 0);
Miheo
  • 517
  • 9
  • 19
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 20 '21 at 09:29
0

You can use JavaScript to scroll to the top:

backtotop.addEventListener("click", () => {
  window.scrollTo({top: 0});
  return false;
});
RoToRa
  • 37,635
  • 12
  • 69
  • 105
0

Maybe you just want to prevent the default behavior.

document.querySelector(".back-to-top").addEventListener("click", (e) => {
    e.preventDefault();
})
0

I listen for hashtags with two listeners: one for within page navigation and one for when a page loads (in the event another page links to a hashed target on a different page).

The hashchange listener removes the hash for within page navigation, and the load listener removes the hash when pages switch.

These listeners remove the hash when "#" is used to scroll or jump to the top of a page. These listeners also remove all other hash tags as well.

The listeners can be adapted to retain parameters after the hash, if needed or desired.

I relied on this discussion: How to remove the hash from window.location (URL) with JavaScript without page refresh?

function removeLocationHash() {
    window.history.replaceState('', document.title, window.location.href.replace(/#.*$/, ''));
}
window.addEventListener('hashchange', function() {
    removeLocationHash();
});
window.addEventListener('load', function() {
    removeLocationHash();
});
Kay
  • 41
  • 6
-1

Use javascript:void(0) instead of #

It will work.