Statistiques
| Révision :

root / tei / js / jquery.scrollTo.js @ 2

Historique | Voir | Annoter | Télécharger (7,44 ko)

1
/**
2
 * jQuery.ScrollTo
3
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
4
 * Dual licensed under MIT and GPL.
5
 * Date: 3/9/2009
6
 *
7
 * @projectDescription Easy element scrolling using jQuery.
8
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
9
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7/8, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
10
 *
11
 * @author Ariel Flesler
12
 * @version 1.4.1
13
 *
14
 * @id jQuery.scrollTo
15
 * @id jQuery.fn.scrollTo
16
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
17
 *          The different options for target are:
18
 *                - A number position (will be applied to all axes).
19
 *                - A string position ('44', '100px', '+=90', etc ) will be applied to all axes
20
 *                - A jQuery/DOM element ( logically, child of the element to scroll )
21
 *                - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
22
 *                - A hash { top:x, left:y }, x and y can be any kind of number/string like above.
23
 *                - The string 'max' for go-to-end. 
24
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
25
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
26
 *         @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
27
 *         @option {Number} duration The OVERALL length of the animation.
28
 *         @option {String} easing The easing method for the animation.
29
 *         @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
30
 *         @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
31
 *         @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
32
 *         @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
33
 *         @option {Function} onAfter Function to be called after the scrolling ends. 
34
 *         @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
35
 * @return {jQuery} Returns the same jQuery object, for chaining.
36
 *
37
 * @desc Scroll to a fixed position
38
 * @example $('div').scrollTo( 340 );
39
 *
40
 * @desc Scroll relatively to the actual position
41
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
42
 *
43
 * @dec Scroll using a selector (relative to the scrolled element)
44
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
45
 *
46
 * @ Scroll to a DOM element (same for jQuery object)
47
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
48
 *                        $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
49
 *                                alert('scrolled!!');                                                                                                                                   
50
 *                        }});
51
 *
52
 * @desc Scroll on both axes, to different values
53
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
54
 */
55
;(function( $ ){
56
        
57
        var $scrollTo = $.scrollTo = function( target, duration, settings ){
58
                $(window).scrollTo( target, duration, settings );
59
        };
60

    
61
        $scrollTo.defaults = {
62
                axis:'xy',
63
                duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
64
        };
65

    
66
        // Returns the element that needs to be animated to scroll the window.
67
        // Kept for backwards compatibility (specially for localScroll & serialScroll)
68
        $scrollTo.window = function( scope ){
69
                return $(window).scrollable();
70
        };
71

    
72
        // Hack, hack, hack... stay away!
73
        // Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
74
        $.fn.scrollable = function(){
75
                return this.map(function(){
76
                        var elem = this,
77
                                isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
78

    
79
                                if( !isWin )
80
                                        return elem;
81

    
82
                        var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
83
                        
84
                        return $.browser.safari || doc.compatMode == 'BackCompat' ?
85
                                doc.body : 
86
                                doc.documentElement;
87
                });
88
        };
89

    
90
        $.fn.scrollTo = function( target, duration, settings ){
91
                if( typeof duration == 'object' ){
92
                        settings = duration;
93
                        duration = 0;
94
                }
95
                if( typeof settings == 'function' )
96
                        settings = { onAfter:settings };
97
                        
98
                if( target == 'max' )
99
                        target = 9e9;
100
                        
101
                settings = $.extend( {}, $scrollTo.defaults, settings );
102
                // Speed is still recognized for backwards compatibility
103
                duration = duration || settings.speed || settings.duration;
104
                // Make sure the settings are given right
105
                settings.queue = settings.queue && settings.axis.length > 1;
106
                
107
                if( settings.queue )
108
                        // Let's keep the overall duration
109
                        duration /= 2;
110
                settings.offset = both( settings.offset );
111
                settings.over = both( settings.over );
112

    
113
                return this.scrollable().each(function(){
114
                        var elem = this,
115
                                $elem = $(elem),
116
                                targ = target, toff, attr = {},
117
                                win = $elem.is('html,body');
118

    
119
                        switch( typeof targ ){
120
                                // A number will pass the regex
121
                                case 'number':
122
                                case 'string':
123
                                        if( /^([+-]=)?\d+(\.\d+)?(px)?$/.test(targ) ){
124
                                                targ = both( targ );
125
                                                // We are done
126
                                                break;
127
                                        }
128
                                        // Relative selector, no break!
129
                                        targ = $(targ,this);
130
                                case 'object':
131
                                        // DOMElement / jQuery
132
                                        if( targ.is || targ.style )
133
                                                // Get the real position of the target 
134
                                                toff = (targ = $(targ)).offset();
135
                        }
136
                        $.each( settings.axis.split(''), function( i, axis ){
137
                                var Pos        = axis == 'x' ? 'Left' : 'Top',
138
                                        pos = Pos.toLowerCase(),
139
                                        key = 'scroll' + Pos,
140
                                        old = elem[key],
141
                                        Dim = axis == 'x' ? 'Width' : 'Height';
142

    
143
                                if( toff ){// jQuery / DOMElement
144
                                        attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );
145

    
146
                                        // If it's a dom element, reduce the margin
147
                                        if( settings.margin ){
148
                                                attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
149
                                                attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
150
                                        }
151
                                        
152
                                        attr[key] += settings.offset[pos] || 0;
153
                                        
154
                                        if( settings.over[pos] )
155
                                                // Scroll to a fraction of its width/height
156
                                                attr[key] += targ[Dim.toLowerCase()]() * settings.over[pos];
157
                                }else
158
                                        attr[key] = targ[pos];
159

    
160
                                // Number or 'number'
161
                                if( /^\d+$/.test(attr[key]) )
162
                                        // Check the limits
163
                                        attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );
164

    
165
                                // Queueing axes
166
                                if( !i && settings.queue ){
167
                                        // Don't waste time animating, if there's no need.
168
                                        if( old != attr[key] )
169
                                                // Intermediate animation
170
                                                animate( settings.onAfterFirst );
171
                                        // Don't animate this axis again in the next iteration.
172
                                        delete attr[key];
173
                                }
174
                        });
175

    
176
                        animate( settings.onAfter );                        
177

    
178
                        function animate( callback ){
179
                                $elem.animate( attr, duration, settings.easing, callback && function(){
180
                                        callback.call(this, target, settings);
181
                                });
182
                        };
183

    
184
                        // Max scrolling position, works on quirks mode
185
                        // It only fails (not too badly) on IE, quirks mode.
186
                        function max( Dim ){
187
                                var scroll = 'scroll'+Dim;
188
                                
189
                                if( !win )
190
                                        return elem[scroll];
191
                                
192
                                var size = 'client' + Dim,
193
                                        html = elem.ownerDocument.documentElement,
194
                                        body = elem.ownerDocument.body;
195

    
196
                                return Math.max( html[scroll], body[scroll] ) 
197
                                         - Math.min( html[size]  , body[size]   );
198
                                        
199
                        };
200

    
201
                }).end();
202
        };
203

    
204
        function both( val ){
205
                return typeof val == 'object' ? val : { top:val, left:val };
206
        };
207

    
208
})( jQuery );