1+ /*!
2+ * $.fn.scrollIntoView - similar to the default browser scrollIntoView
3+ * The default browser behavior always places the element at the top or bottom of its container.
4+ * This override is smart enough to not scroll if the element is already visible.
5+ *
6+ * Copyright 2011 Arwid Bancewicz
7+ * Licensed under the MIT license
8+ * http://www.opensource.org/licenses/mit-license.php
9+ *
10+ * @date 8 May 2011
11+ * @author Arwid Bancewicz http://arwid.ca
12+ * @version 0.1
13+ */
14+ ( function ( $ ) {
15+ $ . fn . scrollIntoView = function ( duration , easing , complete ) {
16+ // The arguments are optional.
17+ // The first argment can be false for no animation or a duration.
18+ // The first argment could also be a map of options.
19+ // Refer to http://api.jquery.com/animate/.
20+ var opts = $ . extend ( { } ,
21+ $ . fn . scrollIntoView . defaults ) ;
22+
23+ // Get options
24+ if ( $ . type ( duration ) == "object" ) {
25+ $ . extend ( opts , duration ) ;
26+ } else if ( $ . type ( duration ) == "number" ) {
27+ $ . extend ( opts , {
28+ duration : duration ,
29+ easing : easing ,
30+ complete : complete
31+ } ) ;
32+ } else if ( duration == false ) {
33+ opts . smooth = false ;
34+ }
35+
36+ // should only be used for one element
37+ if ( this . size ( ) != 1 ) {
38+ return this ;
39+ }
40+
41+ this . each ( function ( ) {
42+ var pEl = this . parentNode ;
43+ var pY = pEl . scrollTop ;
44+ var pH = pEl . clientHeight ;
45+ var elY = this . offsetTop ;
46+ var elH = this . offsetHeight ;
47+ if ( ( elY + elH ) > ( pY + pH ) ) {
48+ // scroll down
49+ if ( opts . smooth ) animateScroll ( $ ( pEl ) , elY + elH - pH ) ;
50+ else pEl . scrollTop = elY + elH - pH ;
51+ } else if ( elY < pY ) {
52+ // scroll up
53+ if ( opts . smooth ) animateScroll ( $ ( pEl ) , elY ) ;
54+ else pEl . scrollTop = elY ;
55+ }
56+ } ) ;
57+
58+ function animateScroll ( el , scrollTo ) {
59+ el . stop ( ) . animate ( {
60+ scrollTop : scrollTo
61+ } ,
62+ opts ) ;
63+ }
64+ return this ;
65+ } ;
66+
67+ $ . fn . scrollIntoView . defaults = {
68+ smooth : true ,
69+ duration : null ,
70+ easing : $ . easing && $ . easing . easeOutExpo ? 'easeOutExpo' : null ,
71+ // Note: easeOutExpo requires jquery.effects.core.js
72+ // otherwise jQuery will default to use 'swing'
73+ complete : $ . noop ( ) ,
74+ step : null ,
75+ specialEasing : null
76+ } ;
77+
78+ } ) ( jQuery ) ;
0 commit comments