Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
Javascript back to top without adding # to the URL

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)
      }
})();
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

Does this answer to your question ?

Make an onClick function with this sample:

window.scrollTo(0, 0);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use JavaScript to scroll to the top:

backtotop.addEventListener("click", () => {
  window.scrollTo({top: 0});
  return false;
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda