2
2
// Animated Scrolling for Same-Page Links
3
3
// @see http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links
4
4
5
- $ . fn . smoothScroll = function ( options ) {
5
+ $ . fn . extend ( {
6
+ smoothScroll : function ( options ) {
6
7
var opts = $ . extend ( { } , $ . fn . smoothScroll . defaults , options ) ,
7
8
locationPath = filterPath ( location . pathname ) ,
8
9
scrollElem = scrollableElement ( 'html' , 'body' ) ;
@@ -15,7 +16,11 @@ $.fn.smoothScroll = function(options) {
15
16
thisHash = link . hash && link . hash . replace ( '#' , '' ) ,
16
17
scrollTargetExists = thisHash && ! ! $ ( '#' + thisHash ) . length ;
17
18
18
- if ( hostMatch && pathMatch && scrollTargetExists ) {
19
+ if ( opts . scrollTarget ) {
20
+ if ( ! / # \S $ / . test ( opts . scrollTarget ) ) { opts . scrollTarget += ':first' ; }
21
+ $link . data ( 'scrollTarget' , opts . scrollTarget ) ;
22
+
23
+ } else if ( hostMatch && pathMatch && scrollTargetExists ) {
19
24
var include = true ,
20
25
21
26
exclude = opts . exclude ,
@@ -41,22 +46,14 @@ $.fn.smoothScroll = function(options) {
41
46
$link . data ( 'scrollTarget' , '#' + thisHash ) ;
42
47
}
43
48
}
44
-
45
49
} ) ;
46
50
47
-
51
+
48
52
this . die ( 'click.smoothscroll' ) . live ( 'click.smoothscroll' , function ( event ) {
49
- var scrollTargetId = $ ( this ) . data ( 'scrollTarget' ) ;
50
- if ( scrollTargetId ) {
51
- event . preventDefault ( ) ;
52
-
53
- var scrollTargetOffset = $ ( scrollTargetId ) . offset ( ) . top ;
54
-
55
- $ ( scrollElem ) . animate ( { scrollTop : scrollTargetOffset + opts . offset } , 400 , function ( ) {
56
- // location.hash = target;
57
- } ) ;
58
- }
53
+ event . preventDefault ( ) ;
54
+ $ ( this ) . smoothScroller ( ) ;
59
55
} ) ;
56
+
60
57
return this ;
61
58
62
59
// private functions
@@ -92,13 +89,38 @@ $.fn.smoothScroll = function(options) {
92
89
window . console . log ( $obj ) ;
93
90
}
94
91
}
95
- } ;
92
+ } ,
93
+
94
+ smoothScroller : function ( link ) {
95
+ var scrollTargetId = $ ( link ) . data ( 'scrollTarget' ) ;
96
+ if ( scrollTargetId ) {
97
+ event . preventDefault ( ) ;
98
+
99
+ var scrollTargetOffset = $ ( scrollTargetId ) . offset ( ) . top ;
100
+
101
+ $ ( scrollElem ) . animate ( {
102
+ scrollTop : scrollTargetOffset + opts . offset
103
+ } ,
104
+ {
105
+ duration : opts . speed ,
106
+ easing : opts . easing
107
+ } , function ( ) {
108
+ opts . afterScroll . call ( link ) ;
109
+ } ) ;
110
+ }
111
+ }
112
+ } ) ;
96
113
97
114
// default options
98
115
$ . fn . smoothScroll . defaults = {
116
+ autobind : true ,
99
117
exclude : [ ] ,
100
118
excludeWithin :[ ] ,
101
- offset : 0
119
+ offset : 0 ,
120
+ scrollTarget : null , // only use if you want to override default behavior
121
+ afterScroll : null , // function to be called after window is scrolled
122
+ easing : 'swing' ,
123
+ speed : 400
102
124
} ;
103
125
104
126
} ) ( jQuery ) ;
0 commit comments