jQuery scroll to Anchor script


/ Published in: jQuery
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. });

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.