Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!