How to transition to a page and scrollTo a specific position

182 views Asked by At

I am working on a school project, and I would like my navbar to link to the index.html page and scroll down to the "About Me" image when clicked. I tried the following JS code:

const pcNav = document.querySelector('#pcAboutButton');
const About = document.querySelector('#aboutImage');

pcNav.addEventListener('click', () => {
  location.href="index.html";
  scrollTo({ behavior: 'smooth', top: About.offsetHeight + 500});
});

The script successfully transitions to the index.html page, but it does not scroll down to the image position. So I changed the code to:

pcNav.addEventListener('click', () => {
  location.href= "index.html";
});

scrollTo({ behavior: 'smooth', top: About.offsetHeight + 500});

However, this now scrolls down every time I visit the index.html page.

1

There are 1 answers

0
Joshua On

One way to achieve this is to include a hash in your URL, which carries extra info for your script to determine whether to scroll down to the "About Me" image when the transition is coming from that about button click event, but also keeps the normal page load behavior if the page transition is not coming from the about button click. See the example below:

On your about page, include a hash in the window.location.href:

const pcNav = document.querySelector('#pcAboutButton');

pcNav.addEventListener('click', () => {
  // Go to index page with the hash value of "about-image"
  location.href = '/#about-image';
});

And on your index page, listen for the window.onload event to check for the hash value:

window.onload = function () {
  if (window.location.hash === '#about-image') {
    window.scrollTo({
      behavior: 'smooth',
      top: document.querySelector('.about-image').offsetTop,
    });
  }
};