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.
In 2018, you don't need jQuery for something simple like this. The built in
[scrollIntoView()][1]
method supports a "behavior
" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:
Great solution by jAndy, but the smooth scroll seems to be having issues working in firefox.
Writing it this way works in Firefox as well.
Most answers are unnecessarily complicated.
If you just want to jump to the target element, you don't need JavaScript:
If you want to scroll to the target animatedly, please refer to @Shahil's answer.
Way simpler:
I know this is question is really old, but I found an easy and simple jQuery solution in css-tricks. That's the one I'm using now.
No jQuery required at all!