jquery.smoothscroll.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*! http://mths.be/smoothscroll v1.5.2 by @mathias */
  2. ;
  3. (function(document, $) {
  4. var $scrollElement = (function() {
  5. // Find out what to scroll (html or body)
  6. var $html = $(document.documentElement),
  7. $body = $(document.body),
  8. bodyScrollTop;
  9. if ($html.scrollTop()) {
  10. return $html;
  11. } else {
  12. bodyScrollTop = $body.scrollTop();
  13. // If scrolling the body doesn’t do anything
  14. if ($body.scrollTop(bodyScrollTop + 1).scrollTop() == bodyScrollTop) {
  15. return $html;
  16. } else {
  17. // We actually scrolled, so undo it
  18. return $body.scrollTop(bodyScrollTop);
  19. }
  20. }
  21. }());
  22. $.fn.smoothScroll = function(speed) {
  23. speed = ~~speed || 400;
  24. // Look for links to anchors (on any page)
  25. return this.find('a[href*="#"]').click(function(event) {
  26. var hash = this.hash,
  27. $hash = $(hash); // The in-document element the link points to
  28. // If it’s a link to an anchor in the same document
  29. if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
  30. // If the anchor actually exists…
  31. if ($hash.length) {
  32. // …don’t jump to the link right away…
  33. event.preventDefault();
  34. // …and smoothly scroll to it
  35. $scrollElement.stop().animate({
  36. 'scrollTop': $hash.offset().top
  37. }, speed, function() {
  38. location.hash = hash;
  39. });
  40. }
  41. }
  42. }).end();
  43. };
  44. }(document, jQuery));