Posted By

e11world on 10/17/10


Tagged

scroll link jquery anchor top target


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

trusktr
dekehooper
Tyster


jQuery scroll to Anchor script


 / Published in: jQuery
 

URL: http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links

This one worked for me and I thought I'd share it with the rest of you!

  1. $(document).ready(function() {
  2. function filterPath(string) {
  3. return string
  4. .replace(/^\//,'')
  5. .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
  6. .replace(/\/$/,'');
  7. }
  8. $('a[href*=#]').each(function() {
  9. if ( filterPath(location.pathname) == filterPath(this.pathname)
  10. && location.hostname == this.hostname
  11. && this.hash.replace(/#/,'') ) {
  12. var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
  13. var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
  14. if ($target) {
  15. var targetOffset = $target.offset().top;
  16. $(this).click(function() {
  17. $('html, body').animate({scrollTop: targetOffset}, 400);
  18. return false;
  19. });
  20. }
  21. }
  22. });
  23. });

Report this snippet  

You need to login to post a comment.