Friday, March 12, 2010

Animated Page Scrolling with jQuery

Many a times we use HTML links to link to some section on the same page and we link them using anchor tags. Using the nifty power of jQuery you can animate this effect by scrolling the page slowly when clicked on the anchor links. I have devised this easy to use function which can be used to scroll the HTML page/window to any HTML element on the page.

The ScrollTo function requires the id of the HTML element you want to scroll to and the duration for how long the animation should run. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. You can even call this function without the duration in which case the default duration is set to 400ms.

Just include the following JavaScript code in the head section of your HTML page:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function ScrollTo(id, duration)
{
      if(!duration) duration = 400;
      var offset = $('#' + id).offset().top;
      $('html,body').animate({scrollTop: offset}, duration);
}
</script>

You can call this ScrollTo function from any DOM event like mouse clicks or key press. It can be used with any HTML element. Just make sure the id you pass to the function should be an unique id of any HTML element on the page.

HTML Examples:
<a href="javascript:void(0)" onclick="ScrollTo('placeToGo', 500)">Go To Link</a>
<a href="javascript:void(0)" onclick="ScrollTo('placeToGo')">Go To Link</a>
<img src="ClickButton.gif" onclick="ScrollTo('placetoGo') />

1 comment:

Thanks a lot for your valuable comments :)