Posted By


realpeterz on 06/01/11

Tagged


Statistics


Viewed 667 times
Favorited by 0 user(s)

Smooth Scrolling


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



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. var locationPath = filterPath(location.pathname);
  9. var scrollElem = scrollableElement('html', 'body');
  10.  
  11. $('a[href*=#]').each(function() {
  12. var thisPath = filterPath(this.pathname) || locationPath;
  13. if ( locationPath == thisPath
  14. && (location.hostname == this.hostname || !this.hostname)
  15. && this.hash.replace(/#/,'') ) {
  16. var $target = $(this.hash), target = this.hash;
  17. if (target) {
  18. var targetOffset = $target.offset().top;
  19. $(this).click(function(event) {
  20. event.preventDefault();
  21. $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
  22. location.hash = target;
  23. });
  24. });
  25. }
  26. }
  27. });
  28.  
  29. // use the first element that is "scrollable"
  30. function scrollableElement(els) {
  31. for (var i = 0, argLength = arguments.length; i <argLength; i++) {
  32. var el = arguments[i],
  33. $scrollElement = $(el);
  34. if ($scrollElement.scrollTop()> 0) {
  35. return el;
  36. } else {
  37. $scrollElement.scrollTop(1);
  38. var isScrollable = $scrollElement.scrollTop()> 0;
  39. $scrollElement.scrollTop(0);
  40. if (isScrollable) {
  41. return el;
  42. }
  43. }
  44. }
  45. return [];
  46. }
  47.  
  48. });

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.