I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.
I have specified a name
or id
attribute in my HTML code:
<a name="anchorName">..</a>
or
<h1 id="anchorName2">..</h1>
I’d like to get the same effect as you’d get by navigating to http://server.com/path#anchorName
. The page should be scrolled so that the anchor is near the top of the visible part of the page.
You can use jQuerys .animate(), .offset() and
scrollTop
. Likeexample link: http://jsbin.com/unasi3/edit
If you don't want to animate use .scrollTop() like
or javascripts native
location.hash
likeThe solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:
I fixed it by changing the selector. The full snippet is this:
2018 Pure js:
There is a very convenient way to scroll to the element:
But as far as I understand he does not have such good support as the options below.
Learn more about the method.
If it is necessary that the element is in the top:
Demonstration example on Codepen
If you want the element to be in the center:
Demonstration example on Codepen
Support:
They write that
scroll
is the same method asscrollTo
, but support shows better inscrollTo
.More about the method
This works:
https://jsfiddle.net/68pnkfgd/
Just add the class 'scroll' to any links you wish to animate