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.
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:And on your index page, listen for the
window.onloadevent to check for the hash value: