I have a large document with numbered anchor tags as shown below. And a textbox to punch the numbers in to go to anchor which uses window.location.hash
I am also using arrow keys to go next or previous anchors. I want to scroll to the anchor so to give some sense of direction.
<a name="1">
some text
<a name="2">
some text
<a name="3">
here is my function
function updatePageNumber()
{
var pagenumber;
pagenumber = document.getElementById('pageNumber').value;
window.location.hash = pagenumber;
}
Jumping to anchor is very ugly and people loose sense of direction in the text. So is there a way to scroll to anchor with JavaScript. I know there are lots of jQuery examples, but I don't know jQuery and couldn't find JavaScript.
Most important reason is I want to see my page number on the address bar!
Smooth scrolling demo
Creating the Smooth Scroll Effect with JavaScript
Use this code and enjoy
You may want to check out this tutorial or google for "JS smooth scroll"
Add jQuery library.
Use the following script to do a smooth scroll to the target element you want.
target
is the id of the target element and1000
is the duration of the animation.There is no built-in smooth scrolling in JavaScript so you would have to implement it yourself -- but why re-invent the wheel if you already have it in jQuery and you probably won't have to add more than two or three lines of code? Just download jQuery and the ScrollTo plugin, add them to your
<head>
section in a<script>
tag and then use this to scroll to an element with a given ID:This will scroll to the element whose ID is
my-element-id
so you have to use theid=...
attribute in the anchors and not thename=...
attribute.If you wish to add this behaviour automatically to all your anchors within a given
div
(or to the entire page), you can use the LocalScroll plugin which makes the entire this as simple as:I know you said that you don't know jQuery, but you are going to want to use it for the scrolling anyways. Here's a simple example of how it could be used.