tags:

views:

52

answers:

2

My homepage has a series of links. When those links are clicked, I want the user to be brought to a certain area of the clicked page. Typically I would use the following HTML on the homepage:

<a href="products.html#link1">LINK</a>

Where #link1 is the div I want to scroll to. This time, I want to use jquery to give it a nice elegant scroll from the top of the page, versus loading directly at that div. So when the anchor is clicked on the homepage, the products page appears and scrolls down to the hashed div. Any help would be appreciated.

+1  A: 

Here's a jQuery plugin that does what you want. It will let you specify what anchor to scroll to, and how long of a duration to scroll, so it can be smooth, quick, etc. Looks easy to implement.

kchau
+2  A: 

You could use scrollTo to achieve this. The difficult part is that the hash needs to be persisted across from the HTTP request to the HTTP response - this could be done using a cookie or possibly local storage (HTML 5), if supported by the browser.

I would probably handle it by

  1. checking if JavaScript is enabled, preventing the default anchor behaviour
  2. checking the href for a hash value. If one exists, persist the value in the storage of choice. If one doesn't exist, it would probably be a good idea to clear the stored value as we don't want to try and scroll to something when the requested page loads.
  3. upon loading the next page, check the value in storage and use the scrollTo plugin to scroll to the element.
Russ Cam