To scroll a newly opened page, use onload
function. but you must use a specific condition in if statement.
In my case, I used the windows.location.href
as a condition.
If the location.href.includes(string added to location.href by clicking the link on the other page ) then onload scroll to (you can use link or coordinates).
here are the steps to make it clear:
1- HTML
add /
after #
so the link will go to the top of the newly opened page. and we will use that as a condition
This link is on a page called work, this link will open index.html page.
<a href="index.html#/work" class="nav-btn-work">WORK</a>
When the new page opens, there will be a #/work
in its location.href
2- Now let's use that in javascript to scroll the newly opened page:
let pageUrl = window.location.href;
if (pageUrl.includes("#/work")) {
setTimeout(() => {
location.href = "#work";
}, 500);
}
// #work is a section in the middle of the new page and after opening the new page, it will scroll to it.
I waited for half a second before scrolling. you can change or remove that.
I hope this helps. it works for me with no errors or problems.