jquery.scrollTo-1.4.3.1.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /*!
  2. * jQuery.ScrollTo
  3. * Copyright (c) 2007-2012 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
  4. * Dual licensed under MIT and GPL.
  5. * Date: 4/09/2012
  6. *
  7. * @projectDescription Easy element scrolling using jQuery.
  8. * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
  9. * @author Ariel Flesler
  10. * @version 1.4.3.1
  11. *
  12. * @id jQuery.scrollTo
  13. * @id jQuery.fn.scrollTo
  14. * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
  15. * The different options for target are:
  16. * - A number position (will be applied to all axes).
  17. * - A string position ('44', '100px', '+=90', etc ) will be applied to all axes
  18. * - A jQuery/DOM element ( logically, child of the element to scroll )
  19. * - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
  20. * - A hash { top:x, left:y }, x and y can be any kind of number/string like above.
  21. * - A percentage of the container's dimension/s, for example: 50% to go to the middle.
  22. * - The string 'max' for go-to-end.
  23. * @param {Number, Function} duration The OVERALL length of the animation, this argument can be the settings object instead.
  24. * @param {Object,Function} settings Optional set of settings or the onAfter callback.
  25. * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
  26. * @option {Number, Function} duration The OVERALL length of the animation.
  27. * @option {String} easing The easing method for the animation.
  28. * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
  29. * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
  30. * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
  31. * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
  32. * @option {Function} onAfter Function to be called after the scrolling ends.
  33. * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
  34. * @return {jQuery} Returns the same jQuery object, for chaining.
  35. *
  36. * @desc Scroll to a fixed position
  37. * @example $('div').scrollTo( 340 );
  38. *
  39. * @desc Scroll relatively to the actual position
  40. * @example $('div').scrollTo( '+=340px', { axis:'y' } );
  41. *
  42. * @desc Scroll using a selector (relative to the scrolled element)
  43. * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
  44. *
  45. * @desc Scroll to a DOM element (same for jQuery object)
  46. * @example var second_child = document.getElementById('container').firstChild.nextSibling;
  47. * $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
  48. * alert('scrolled!!');
  49. * }});
  50. *
  51. * @desc Scroll on both axes, to different values
  52. * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
  53. */
  54. ;(function( $ ){
  55. var $scrollTo = $.scrollTo = function( target, duration, settings ){
  56. $(window).scrollTo( target, duration, settings );
  57. };
  58. $scrollTo.defaults = {
  59. axis:'xy',
  60. duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1,
  61. limit:true
  62. };
  63. // Returns the element that needs to be animated to scroll the window.
  64. // Kept for backwards compatibility (specially for localScroll & serialScroll)
  65. $scrollTo.window = function( scope ){
  66. return $(window)._scrollable();
  67. };
  68. // Hack, hack, hack :)
  69. // Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
  70. $.fn._scrollable = function(){
  71. return this.map(function(){
  72. var elem = this,
  73. isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
  74. if( !isWin )
  75. return elem;
  76. var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
  77. return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
  78. doc.body :
  79. doc.documentElement;
  80. });
  81. };
  82. $.fn.scrollTo = function( target, duration, settings ){
  83. if( typeof duration == 'object' ){
  84. settings = duration;
  85. duration = 0;
  86. }
  87. if( typeof settings == 'function' )
  88. settings = { onAfter:settings };
  89. if( target == 'max' )
  90. target = 9e9;
  91. settings = $.extend( {}, $scrollTo.defaults, settings );
  92. // Speed is still recognized for backwards compatibility
  93. duration = duration || settings.duration;
  94. // Make sure the settings are given right
  95. settings.queue = settings.queue && settings.axis.length > 1;
  96. if( settings.queue )
  97. // Let's keep the overall duration
  98. duration /= 2;
  99. settings.offset = both( settings.offset );
  100. settings.over = both( settings.over );
  101. return this._scrollable().each(function(){
  102. // Null target yields nothing, just like jQuery does
  103. if (target == null) return;
  104. var elem = this,
  105. $elem = $(elem),
  106. targ = target, toff, attr = {},
  107. win = $elem.is('html,body');
  108. switch( typeof targ ){
  109. // A number will pass the regex
  110. case 'number':
  111. case 'string':
  112. if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
  113. targ = both( targ );
  114. // We are done
  115. break;
  116. }
  117. // Relative selector, no break!
  118. targ = $(targ,this);
  119. if (!targ.length) return;
  120. case 'object':
  121. // DOMElement / jQuery
  122. if( targ.is || targ.style )
  123. // Get the real position of the target
  124. toff = (targ = $(targ)).offset();
  125. }
  126. $.each( settings.axis.split(''), function( i, axis ){
  127. var Pos = axis == 'x' ? 'Left' : 'Top',
  128. pos = Pos.toLowerCase(),
  129. key = 'scroll' + Pos,
  130. old = elem[key],
  131. max = $scrollTo.max(elem, axis);
  132. if( toff ){// jQuery / DOMElement
  133. attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );
  134. // If it's a dom element, reduce the margin
  135. if( settings.margin ){
  136. attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
  137. attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
  138. }
  139. attr[key] += settings.offset[pos] || 0;
  140. if( settings.over[pos] )
  141. // Scroll to a fraction of its width/height
  142. attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
  143. }else{
  144. var val = targ[pos];
  145. // Handle percentage values
  146. attr[key] = val.slice && val.slice(-1) == '%' ?
  147. parseFloat(val) / 100 * max
  148. : val;
  149. }
  150. // Number or 'number'
  151. if( settings.limit && /^\d+$/.test(attr[key]) )
  152. // Check the limits
  153. attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );
  154. // Queueing axes
  155. if( !i && settings.queue ){
  156. // Don't waste time animating, if there's no need.
  157. if( old != attr[key] )
  158. // Intermediate animation
  159. animate( settings.onAfterFirst );
  160. // Don't animate this axis again in the next iteration.
  161. delete attr[key];
  162. }
  163. });
  164. animate( settings.onAfter );
  165. function animate( callback ){
  166. $elem.animate( attr, duration, settings.easing, callback && function(){
  167. callback.call(this, target, settings);
  168. });
  169. };
  170. }).end();
  171. };
  172. // Max scrolling position, works on quirks mode
  173. // It only fails (not too badly) on IE, quirks mode.
  174. $scrollTo.max = function( elem, axis ){
  175. var Dim = axis == 'x' ? 'Width' : 'Height',
  176. scroll = 'scroll'+Dim;
  177. if( !$(elem).is('html,body') )
  178. return elem[scroll] - $(elem)[Dim.toLowerCase()]();
  179. var size = 'client' + Dim,
  180. html = elem.ownerDocument.documentElement,
  181. body = elem.ownerDocument.body;
  182. return Math.max( html[scroll], body[scroll] )
  183. - Math.min( html[size] , body[size] );
  184. };
  185. function both( val ){
  186. return typeof val == 'object' ? val : { top:val, left:val };
  187. };
  188. })( jQuery );