Posted By


dubogii on 05/17/11

Tagged


Statistics


Viewed 584 times
Favorited by 0 user(s)

Smooth Scrolling


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

DEMO: http://css-tricks.com/examples/SmoothPageScroll/


Copy this code and paste it in your HTML
  1. Performs a smooth page scroll to an anchor on the same page.
  2.  
  3. $(document).ready(function() {
  4. function filterPath(string) {
  5. return string
  6. .replace(/^\//,'')
  7. .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
  8. .replace(/\/$/,'');
  9. }
  10. var locationPath = filterPath(location.pathname);
  11. var scrollElem = scrollableElement('html', 'body');
  12.  
  13. $('a[href*=#]').each(function() {
  14. var thisPath = filterPath(this.pathname) || locationPath;
  15. if ( locationPath == thisPath
  16. && (location.hostname == this.hostname || !this.hostname)
  17. && this.hash.replace(/#/,'') ) {
  18. var $target = $(this.hash), target = this.hash;
  19. if (target) {
  20. var targetOffset = $target.offset().top;
  21. $(this).click(function(event) {
  22. event.preventDefault();
  23. $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
  24. location.hash = target;
  25. });
  26. });
  27. }
  28. }
  29. });
  30.  
  31. // use the first element that is "scrollable"
  32. function scrollableElement(els) {
  33. for (var i = 0, argLength = arguments.length; i <argLength; i++) {
  34. var el = arguments[i],
  35. $scrollElement = $(el);
  36. if ($scrollElement.scrollTop()> 0) {
  37. return el;
  38. } else {
  39. $scrollElement.scrollTop(1);
  40. var isScrollable = $scrollElement.scrollTop()> 0;
  41. $scrollElement.scrollTop(0);
  42. if (isScrollable) {
  43. return el;
  44. }
  45. }
  46. }
  47. return [];
  48. }
  49.  
  50. });

URL: http://css-tricks.com/snippets/jquery/smooth-scrolling/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.