jquery.sticky.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Sticky Plugin v1.0.3 for jQuery
  2. // =============
  3. // Author: Anthony Garand
  4. // Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
  5. // Improvements by Leonardo C. Daronco (daronco)
  6. // Created: 02/14/2011
  7. // Date: 07/20/2015
  8. // Website: http://stickyjs.com/
  9. // Description: Makes an element on the page stick on the screen as you scroll
  10. // It will only set the 'top' and 'position' of your element, you
  11. // might need to adjust the width in some cases.
  12. (function (factory) {
  13. if (typeof define === 'function' && define.amd) {
  14. // AMD. Register as an anonymous module.
  15. define(['jquery'], factory);
  16. } else if (typeof module === 'object' && module.exports) {
  17. // Node/CommonJS
  18. module.exports = factory(require('jquery'));
  19. } else {
  20. // Browser globals
  21. factory(jQuery);
  22. }
  23. }(function ($) {
  24. var slice = Array.prototype.slice; // save ref to original slice()
  25. var splice = Array.prototype.splice; // save ref to original slice()
  26. var defaults = {
  27. topSpacing: 0,
  28. bottomSpacing: 0,
  29. className: 'is-sticky',
  30. wrapperClassName: 'sticky-wrapper',
  31. center: false,
  32. getWidthFrom: '',
  33. widthFromWrapper: true, // works only when .getWidthFrom is empty
  34. responsiveWidth: false
  35. },
  36. $window = $(window),
  37. $document = $(document),
  38. sticked = [],
  39. windowHeight = $window.height(),
  40. scroller = function() {
  41. var scrollTop = $window.scrollTop(),
  42. documentHeight = $document.height(),
  43. dwh = documentHeight - windowHeight,
  44. extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
  45. for (var i = 0, l = sticked.length; i < l; i++) {
  46. var s = sticked[i],
  47. elementTop = s.stickyWrapper.offset().top,
  48. etse = elementTop - s.topSpacing - extra;
  49. //update height in case of dynamic content
  50. s.stickyWrapper.css('height', s.stickyElement.outerHeight());
  51. if (scrollTop <= etse) {
  52. if (s.currentTop !== null) {
  53. s.stickyElement
  54. .css({
  55. 'width': '',
  56. 'position': '',
  57. 'top': ''
  58. });
  59. s.stickyElement.parent().removeClass(s.className);
  60. s.stickyElement.trigger('sticky-end', [s]);
  61. s.currentTop = null;
  62. }
  63. }
  64. else {
  65. var newTop = documentHeight - s.stickyElement.outerHeight()
  66. - s.topSpacing - s.bottomSpacing - scrollTop - extra;
  67. if (newTop < 0) {
  68. newTop = newTop + s.topSpacing;
  69. } else {
  70. newTop = s.topSpacing;
  71. }
  72. if (s.currentTop !== newTop) {
  73. var newWidth;
  74. if (s.getWidthFrom) {
  75. newWidth = $(s.getWidthFrom).width() || null;
  76. } else if (s.widthFromWrapper) {
  77. newWidth = s.stickyWrapper.width();
  78. }
  79. if (newWidth == null) {
  80. newWidth = s.stickyElement.width();
  81. }
  82. s.stickyElement
  83. .css('width', newWidth)
  84. .css('position', 'fixed')
  85. .css('top', newTop);
  86. s.stickyElement.parent().addClass(s.className);
  87. if (s.currentTop === null) {
  88. s.stickyElement.trigger('sticky-start', [s]);
  89. } else {
  90. // sticky is started but it have to be repositioned
  91. s.stickyElement.trigger('sticky-update', [s]);
  92. }
  93. if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) {
  94. // just reached bottom || just started to stick but bottom is already reached
  95. s.stickyElement.trigger('sticky-bottom-reached', [s]);
  96. } else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) {
  97. // sticky is started && sticked at topSpacing && overflowing from top just finished
  98. s.stickyElement.trigger('sticky-bottom-unreached', [s]);
  99. }
  100. s.currentTop = newTop;
  101. }
  102. // Check if sticky has reached end of container and stop sticking
  103. var stickyWrapperContainer = s.stickyWrapper.parent();
  104. var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + stickyWrapperContainer.outerHeight()) && (s.stickyElement.offset().top <= s.topSpacing);
  105. if( unstick ) {
  106. s.stickyElement
  107. .css('position', 'absolute')
  108. .css('top', '')
  109. .css('bottom', 0);
  110. } else {
  111. s.stickyElement
  112. .css('position', 'fixed')
  113. .css('top', newTop)
  114. .css('bottom', '');
  115. }
  116. }
  117. }
  118. },
  119. resizer = function() {
  120. windowHeight = $window.height();
  121. for (var i = 0, l = sticked.length; i < l; i++) {
  122. var s = sticked[i];
  123. var newWidth = null;
  124. if (s.getWidthFrom) {
  125. if (s.responsiveWidth) {
  126. newWidth = $(s.getWidthFrom).width();
  127. }
  128. } else if(s.widthFromWrapper) {
  129. newWidth = s.stickyWrapper.width();
  130. }
  131. if (newWidth != null) {
  132. s.stickyElement.css('width', newWidth);
  133. }
  134. }
  135. },
  136. methods = {
  137. init: function(options) {
  138. var o = $.extend({}, defaults, options);
  139. return this.each(function() {
  140. var stickyElement = $(this);
  141. var stickyId = stickyElement.attr('id');
  142. var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName;
  143. var wrapper = $('<div></div>')
  144. .attr('id', wrapperId)
  145. .addClass(o.wrapperClassName);
  146. stickyElement.wrapAll(wrapper);
  147. var stickyWrapper = stickyElement.parent();
  148. if (o.center) {
  149. stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
  150. }
  151. if (stickyElement.css("float") === "right") {
  152. stickyElement.css({"float":"none"}).parent().css({"float":"right"});
  153. }
  154. o.stickyElement = stickyElement;
  155. o.stickyWrapper = stickyWrapper;
  156. o.currentTop = null;
  157. sticked.push(o);
  158. methods.setWrapperHeight(this);
  159. methods.setupChangeListeners(this);
  160. });
  161. },
  162. setWrapperHeight: function(stickyElement) {
  163. var element = $(stickyElement);
  164. var stickyWrapper = element.parent();
  165. if (stickyWrapper) {
  166. stickyWrapper.css('height', element.outerHeight());
  167. }
  168. },
  169. setupChangeListeners: function(stickyElement) {
  170. if (window.MutationObserver) {
  171. var mutationObserver = new window.MutationObserver(function(mutations) {
  172. if (mutations[0].addedNodes.length || mutations[0].removedNodes.length) {
  173. methods.setWrapperHeight(stickyElement);
  174. }
  175. });
  176. mutationObserver.observe(stickyElement, {subtree: true, childList: true});
  177. } else {
  178. stickyElement.addEventListener('DOMNodeInserted', function() {
  179. methods.setWrapperHeight(stickyElement);
  180. }, false);
  181. stickyElement.addEventListener('DOMNodeRemoved', function() {
  182. methods.setWrapperHeight(stickyElement);
  183. }, false);
  184. }
  185. },
  186. update: scroller,
  187. unstick: function(options) {
  188. return this.each(function() {
  189. var that = this;
  190. var unstickyElement = $(that);
  191. var removeIdx = -1;
  192. var i = sticked.length;
  193. while (i-- > 0) {
  194. if (sticked[i].stickyElement.get(0) === that) {
  195. splice.call(sticked,i,1);
  196. removeIdx = i;
  197. }
  198. }
  199. if(removeIdx !== -1) {
  200. unstickyElement.unwrap();
  201. unstickyElement
  202. .css({
  203. 'width': '',
  204. 'position': '',
  205. 'top': '',
  206. 'float': ''
  207. })
  208. ;
  209. }
  210. });
  211. }
  212. };
  213. // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  214. if (window.addEventListener) {
  215. window.addEventListener('scroll', scroller, false);
  216. window.addEventListener('resize', resizer, false);
  217. } else if (window.attachEvent) {
  218. window.attachEvent('onscroll', scroller);
  219. window.attachEvent('onresize', resizer);
  220. }
  221. $.fn.sticky = function(method) {
  222. if (methods[method]) {
  223. return methods[method].apply(this, slice.call(arguments, 1));
  224. } else if (typeof method === 'object' || !method ) {
  225. return methods.init.apply( this, arguments );
  226. } else {
  227. $.error('Method ' + method + ' does not exist on jQuery.sticky');
  228. }
  229. };
  230. $.fn.unstick = function(method) {
  231. if (methods[method]) {
  232. return methods[method].apply(this, slice.call(arguments, 1));
  233. } else if (typeof method === 'object' || !method ) {
  234. return methods.unstick.apply( this, arguments );
  235. } else {
  236. $.error('Method ' + method + ' does not exist on jQuery.sticky');
  237. }
  238. };
  239. $(function() {
  240. setTimeout(scroller, 0);
  241. });
  242. }));