Haris
Haris

Reputation: 1

Load back to homepage on refresh

I have a single page website. If click one of the navbar tabs, lets say 'contact us' the site will scroll down to the contact section. The problem is, if I refresh the site now it will automatically scroll down to the contact section each time. I want the site to scroll to the top of the page every time I refresh. The reason this is happening is because the address bar is changed to ...index.html#contact-area.

I tried the code below but the site gets caught in an infinite refresh loop.

<script>
        window.location.replace("index.html");
</script>

I also tried the following but it doesn't work. It starts to scroll up then stops.

<script>
        window.onbeforeunload = function () {
        window.scrollTo(0, 0);
        }
</script>

Upvotes: 0

Views: 979

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370809

One option is to attach an event listener to the anchor instead, and instead of changing the page hash, call scrollIntoView on the #contact-area:

anchor.addEventListener('e', (e) => {
  e.preventDefault(); // don't change page hash (unless JS disabled...)
  document.querySelector('#contact-area').scrollIntoView();
});

Upvotes: 2

Related Questions