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

169
Visualizações
JS scrolling back to top after window.scroll

Hihi, I need that when I visit my webpage and # is present in the url go to that section. So What I did is to add an JS script

document.addEventListener('DOMContentLoaded', () => {
    // setupScrolling();
    setupTitle();
    if (window.location.hash) {
        const element = document.getElementById(window.location.hash);
        if (element) {
            const offset = element.offsetTop;
            const a = offset - (document.querySelector('header')?.offsetHeight);
            window.scroll({
                top: offset,
                behavior: 'smooth'
            });
            return false;
        }
    }
});

This is the script I added into my public/index.html

But, the behavior isn't correct.. Once the page scroll down to the section it will automatically go back to the top of the site and I don't know why.

Can anyone help me and tell me what I should do?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You don't really need javascript to do this. You can only use HTML.
Simply add an id to the elements you want to allow users to jump to.
Then, when the id of an element is present in your webpage URL as a hash, the page will be directly scrolled to it when the page is loaded.

For example, let say I've got an element with the id 'down-section'

<span id="down-section">Down Section in the page</span>

Access to the link https://your-domaine.com#down-section will directly jump to "Down Section in the page".

Add a smooth behavior.

You may want to add smooth behavior in this particular case. Just add a code like this to your javascript script:

if (!!document.location.hash){
    document.getElementsByTagName('html')[0].style.scrollBehavior = 'smooth';
}
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