Tuesday, March 22, 2011

How to Jump to an Anchor using JavaScript

Just like links/urls are a great way of moving between pages, anchors are great way of moving between locations on the same page.
Suppose we would like to move to a specific location on a page above some <div> tag. All we have to do is simply put an <a> tag above that div and give it some name. For example:
<a name="example"></a>
<div>
...
...
...
</div>

How do we jump to this specific location (named: example)? By putting an <a> on the place from which we would like to jump to this location. For example, somewhere else on the page we put:

<a href="#example">Press here to show example</a>

Note, that the name of the anchor for which we would like to jump contains the hash sign (#) as a prefix.

Now, suppose we would like to jump to some location by clicking something other than <a> (anchor) tag. For example by clicking a simple button. How can we jump to that location? Since we are not using anchor tag, we can no longer be directed to that location automatically.

We can use JavaScript in order to accomplish exactly the same behavior. Let’s see how it can be easily done with our button and by setting the “window.location.hash” property :

<input type="button" value="Press here to show example" onclick="window.location.hash = 'example';"/>

Note that on the JavaScript code we no longer need to use the hash (#) prefix.

No comments:

Post a Comment