|
| 1 | +/**! |
| 2 | + * @author Steve Piron <https://twitter.com/stevepiron> |
| 3 | + * @requires jQuery |
| 4 | + * |
| 5 | + * A jQuery plugin that will animate page jumps to anchors. |
| 6 | + */ |
| 7 | +(function( $ ) { |
| 8 | + |
| 9 | + var defaults; |
| 10 | + var params; |
| 11 | + |
| 12 | + var $body = $('body'); |
| 13 | + |
| 14 | + // ====================================================================== // |
| 15 | + // Functions |
| 16 | + // ====================================================================== // |
| 17 | + |
| 18 | + /** |
| 19 | + * @function `scrollToTarget` |
| 20 | + * |
| 21 | + * Scrolls through the page to the defined target. |
| 22 | + * |
| 23 | + * @param $link {jQuery} - the clicked link. |
| 24 | + */ |
| 25 | + function scrollToTarget( $link ) { |
| 26 | + var $target = $($link.attr('href')); |
| 27 | + |
| 28 | + params.container.animate({ |
| 29 | + scrollTop: $target.offset().top - params.offset |
| 30 | + }, params.scrollSpeed); |
| 31 | + } |
| 32 | + |
| 33 | + // ====================================================================== // |
| 34 | + // Plugin |
| 35 | + // ====================================================================== // |
| 36 | + |
| 37 | + $.fn.spScrollTo = function( options ) { |
| 38 | + |
| 39 | + /** |
| 40 | + * Note: using `return` keeps jQuery's chaining possibility |
| 41 | + */ |
| 42 | + return this.each(function() { |
| 43 | + |
| 44 | + defaults = { |
| 45 | + container: $body, |
| 46 | + offset: 0, |
| 47 | + scrollSpeed: 800, |
| 48 | + onBeforeScroll: undefined |
| 49 | + }; |
| 50 | + |
| 51 | + params = $.extend( defaults, options ); |
| 52 | + |
| 53 | + var $this = $(this); |
| 54 | + |
| 55 | + // ============================================================== // |
| 56 | + // On click |
| 57 | + // ============================================================== // |
| 58 | + |
| 59 | + $this.on('click', function(e) { |
| 60 | + e.preventDefault(); |
| 61 | + if( typeof params.onBeforeScroll == 'function' ) { |
| 62 | + params.onBeforeScroll(e); |
| 63 | + } |
| 64 | + scrollToTarget( $this ); |
| 65 | + return; |
| 66 | + }); |
| 67 | + |
| 68 | + }); |
| 69 | + }; |
| 70 | + |
| 71 | +}( jQuery )); |
0 commit comments