sticky.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // Sticky Plugin v1.0.4 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. zIndex: 'auto'
  36. },
  37. $window = $(window),
  38. $document = $(document),
  39. sticked = [],
  40. windowHeight = $window.height(),
  41. scroller = function() {
  42. var scrollTop = $window.scrollTop(),
  43. documentHeight = $document.height(),
  44. dwh = documentHeight - windowHeight,
  45. extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
  46. for (var i = 0, l = sticked.length; i < l; i++) {
  47. var s = sticked[i],
  48. elementTop = s.stickyWrapper.offset().top,
  49. etse = elementTop - s.topSpacing - extra;
  50. //update height in case of dynamic content
  51. s.stickyWrapper.css('height', s.stickyElement.outerHeight());
  52. if (scrollTop <= etse) {
  53. if (s.currentTop !== null) {
  54. s.stickyElement
  55. .css({
  56. 'width': '',
  57. 'position': '',
  58. 'top': '',
  59. 'z-index': ''
  60. });
  61. s.stickyElement.parent().removeClass(s.className);
  62. s.stickyElement.trigger('sticky-end', [s]);
  63. s.currentTop = null;
  64. }
  65. }
  66. else {
  67. var newTop = documentHeight - s.stickyElement.outerHeight()
  68. - s.topSpacing - s.bottomSpacing - scrollTop - extra;
  69. if (newTop < 0) {
  70. newTop = newTop + s.topSpacing;
  71. } else {
  72. newTop = s.topSpacing;
  73. }
  74. if (s.currentTop !== newTop) {
  75. var newWidth;
  76. if (s.getWidthFrom) {
  77. newWidth = $(s.getWidthFrom).width() || null;
  78. } else if (s.widthFromWrapper) {
  79. newWidth = s.stickyWrapper.width();
  80. }
  81. if (newWidth == null) {
  82. newWidth = s.stickyElement.width();
  83. }
  84. s.stickyElement
  85. .css('width', newWidth)
  86. .css('position', 'fixed')
  87. .css('top', newTop)
  88. .css('z-index', s.zIndex);
  89. s.stickyElement.parent().addClass(s.className);
  90. if (s.currentTop === null) {
  91. s.stickyElement.trigger('sticky-start', [s]);
  92. } else {
  93. // sticky is started but it have to be repositioned
  94. s.stickyElement.trigger('sticky-update', [s]);
  95. }
  96. if (s.currentTop === s.topSpacing && s.currentTop > newTop || s.currentTop === null && newTop < s.topSpacing) {
  97. // just reached bottom || just started to stick but bottom is already reached
  98. s.stickyElement.trigger('sticky-bottom-reached', [s]);
  99. } else if(s.currentTop !== null && newTop === s.topSpacing && s.currentTop < newTop) {
  100. // sticky is started && sticked at topSpacing && overflowing from top just finished
  101. s.stickyElement.trigger('sticky-bottom-unreached', [s]);
  102. }
  103. s.currentTop = newTop;
  104. }
  105. // Check if sticky has reached end of container and stop sticking
  106. var stickyWrapperContainer = s.stickyWrapper.parent();
  107. var unstick = (s.stickyElement.offset().top + s.stickyElement.outerHeight() >= stickyWrapperContainer.offset().top + stickyWrapperContainer.outerHeight()) && (s.stickyElement.offset().top <= s.topSpacing);
  108. if( unstick ) {
  109. s.stickyElement
  110. .css('position', 'absolute')
  111. .css('top', '')
  112. .css('bottom', 0)
  113. .css('z-index', '');
  114. } else {
  115. s.stickyElement
  116. .css('position', 'fixed')
  117. .css('top', newTop)
  118. .css('bottom', '')
  119. .css('z-index', s.zIndex);
  120. }
  121. }
  122. }
  123. },
  124. resizer = function() {
  125. windowHeight = $window.height();
  126. for (var i = 0, l = sticked.length; i < l; i++) {
  127. var s = sticked[i];
  128. var newWidth = null;
  129. if (s.getWidthFrom) {
  130. if (s.responsiveWidth) {
  131. newWidth = $(s.getWidthFrom).width();
  132. }
  133. } else if(s.widthFromWrapper) {
  134. newWidth = s.stickyWrapper.width();
  135. }
  136. if (newWidth != null) {
  137. s.stickyElement.css('width', newWidth);
  138. }
  139. }
  140. },
  141. methods = {
  142. init: function(options) {
  143. return this.each(function() {
  144. var o = $.extend({}, defaults, options);
  145. var stickyElement = $(this);
  146. var stickyId = stickyElement.attr('id');
  147. var wrapperId = stickyId ? stickyId + '-' + defaults.wrapperClassName : defaults.wrapperClassName;
  148. var wrapper = $('<div></div>')
  149. .attr('id', wrapperId)
  150. .addClass(o.wrapperClassName);
  151. stickyElement.wrapAll(function() {
  152. if ($(this).parent("#" + wrapperId).length == 0) {
  153. return wrapper;
  154. }
  155. });
  156. var stickyWrapper = stickyElement.parent();
  157. if (o.center) {
  158. stickyWrapper.css({width:stickyElement.outerWidth(),marginLeft:"auto",marginRight:"auto"});
  159. }
  160. if (stickyElement.css("float") === "right") {
  161. stickyElement.css({"float":"none"}).parent().css({"float":"right"});
  162. }
  163. o.stickyElement = stickyElement;
  164. o.stickyWrapper = stickyWrapper;
  165. o.currentTop = null;
  166. sticked.push(o);
  167. methods.setWrapperHeight(this);
  168. methods.setupChangeListeners(this);
  169. });
  170. },
  171. setWrapperHeight: function(stickyElement) {
  172. var element = $(stickyElement);
  173. var stickyWrapper = element.parent();
  174. if (stickyWrapper) {
  175. stickyWrapper.css('height', element.outerHeight());
  176. }
  177. },
  178. setupChangeListeners: function(stickyElement) {
  179. if (window.MutationObserver) {
  180. var mutationObserver = new window.MutationObserver(function(mutations) {
  181. if (mutations[0].addedNodes.length || mutations[0].removedNodes.length) {
  182. methods.setWrapperHeight(stickyElement);
  183. }
  184. });
  185. mutationObserver.observe(stickyElement, {subtree: true, childList: true});
  186. } else {
  187. if (window.addEventListener) {
  188. stickyElement.addEventListener('DOMNodeInserted', function() {
  189. methods.setWrapperHeight(stickyElement);
  190. }, false);
  191. stickyElement.addEventListener('DOMNodeRemoved', function() {
  192. methods.setWrapperHeight(stickyElement);
  193. }, false);
  194. } else if (window.attachEvent) {
  195. stickyElement.attachEvent('onDOMNodeInserted', function() {
  196. methods.setWrapperHeight(stickyElement);
  197. });
  198. stickyElement.attachEvent('onDOMNodeRemoved', function() {
  199. methods.setWrapperHeight(stickyElement);
  200. });
  201. }
  202. }
  203. },
  204. update: scroller,
  205. unstick: function(options) {
  206. return this.each(function() {
  207. var that = this;
  208. var unstickyElement = $(that);
  209. var removeIdx = -1;
  210. var i = sticked.length;
  211. while (i-- > 0) {
  212. if (sticked[i].stickyElement.get(0) === that) {
  213. splice.call(sticked,i,1);
  214. removeIdx = i;
  215. }
  216. }
  217. if(removeIdx !== -1) {
  218. unstickyElement.unwrap();
  219. unstickyElement
  220. .css({
  221. 'width': '',
  222. 'position': '',
  223. 'top': '',
  224. 'float': '',
  225. 'z-index': ''
  226. })
  227. ;
  228. }
  229. });
  230. }
  231. };
  232. // should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  233. if (window.addEventListener) {
  234. window.addEventListener('scroll', scroller, false);
  235. window.addEventListener('resize', resizer, false);
  236. } else if (window.attachEvent) {
  237. window.attachEvent('onscroll', scroller);
  238. window.attachEvent('onresize', resizer);
  239. }
  240. $.fn.sticky = function(method) {
  241. if (methods[method]) {
  242. return methods[method].apply(this, slice.call(arguments, 1));
  243. } else if (typeof method === 'object' || !method ) {
  244. return methods.init.apply( this, arguments );
  245. } else {
  246. $.error('Method ' + method + ' does not exist on jQuery.sticky');
  247. }
  248. };
  249. $.fn.unstick = function(method) {
  250. if (methods[method]) {
  251. return methods[method].apply(this, slice.call(arguments, 1));
  252. } else if (typeof method === 'object' || !method ) {
  253. return methods.unstick.apply( this, arguments );
  254. } else {
  255. $.error('Method ' + method + ' does not exist on jQuery.sticky');
  256. }
  257. };
  258. $(function() {
  259. setTimeout(scroller, 0);
  260. });
  261. }));