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!
I do not know your html structure completely
Maybe this method will help you :
Going on the assumption that you want a smooth scroll to a specific position on the same page, you could setup your HTML as tacoshy recommended, using an anchor for the place you’ll click and a reference
#id
for your destination:Then, if you’re using jQuery on your page, you can add a listener to the anchor tag:
the
- 50
is to offset the top of the scroll position from a fixed header, if you have one.If you’re not using jQuery, there is a pure JavaScript solution on GitHub that you might be able to adapt for what you need.
As for your original function
window.scrollTo({ top: 300, left: 0, behavior: "smooth" });
I think that’s always going to bring you to a position 300 pixels from the top of the window, and may not work for IE or Safari (I don’t think they support the options version of scrollTo).