Scrolling to specific position with Javascript failed

I’m new to HTML and Javascript and want to create a link that, when clicked on, scrolls to a specific position in the page. I made some research online and came up with the following solution:

My HTML file:

...
<a href="#" onclick="scroll()">My link</a>
...

My Javascript (which I include in the <head> tag):

function scroll() {
    window.scrollTo({ top: 300, left: 0, behavior: "smooth" });
}

However this does not work well, because every time I click the link, the page just scrolls to the very top of the page, regardless to what position I set in window.scrollTo. Can somebody point out where my mistake is and how to do it right?

Thanks!

13 thoughts on “Scrolling to specific position with Javascript failed”

Leave a Comment