0

I created a smooth scroll with javascript. I made it ok for scrolling within page. But, when coming from another page, it goes to # position directory, then, starts animation. It's written in snippet if (urlHash) {} area.

I'd like the page to show up the top of body first, then, move to the link positions after 1 second, when coming from another page like clicking on index.html#block02.

I can't figure it out. Please help. Thanks a lot.

const anchors = document.querySelectorAll('a[href^="#"]');
const header = document.querySelector('header').offsetHeight;
const urlHash = location.hash;

for ( let i = 0; i < anchors.length; i++ ) {
  anchors[i].addEventListener('click', (e) => {
    e.preventDefault();

    const href= anchors[i].getAttribute("href");

    if (href !== '#top') {

      const target = document.getElementById(href.replace('#', ''));

      const position = window.pageYOffset + target.getBoundingClientRect().top - header;

      window.scroll({
        top: position,
        behavior: 'smooth'
      });

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

    }
  });
}

window.addEventListener('DOMContentLoaded', (event) => {
  if (urlHash) {
    window.scrollTo({top:0});
    setTimeout(function () {

      const urlTarget = document.getElementById(urlHash.replace('#', ''));

      const urlPosition = window.pageYOffset + urlTarget.getBoundingClientRect().top - header;
      window.scroll({
        top: urlPosition,
        behavior: 'smooth'
      });
    }, 1000);
  }
});
header {position: fixed; width:100%; height: 100px; text-align:center; border-bottom:1px solid #ccc;}
div {height: 200vh;}
a {display: inline-block;}
main{padding-top: 100px;}
<header>header</header>
<main>
<a href="#block01">block01へ移動</a>
<a href="#block02">block02へ移動</a>

<div id="block01">block01</div>
<div id="block02">block02</div>

<a href="#top">topへ戻る</a>
</main>

1 Answer 1

1

Just reset scroll position at the top of your script:

setTimeout(() => { window.scrollTo(0, 0) }, 0) // Here

const anchors = document.querySelectorAll('a[href^="#"]');
const header = document.querySelector('header').offsetHeight;
const urlHash = location.hash;
// ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.