You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

775 lines
24 KiB

10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
  1. /*
  2. * # Semantic - Sticky
  3. * http://github.com/semantic-org/semantic-ui/
  4. *
  5. *
  6. * Copyright 2014 Contributors
  7. * Released under the MIT license
  8. * http://opensource.org/licenses/MIT
  9. *
  10. */
  11. ;(function ( $, window, document, undefined ) {
  12. "use strict";
  13. $.fn.sticky = function(parameters) {
  14. var
  15. $allModules = $(this),
  16. moduleSelector = $allModules.selector || '',
  17. time = new Date().getTime(),
  18. performance = [],
  19. query = arguments[0],
  20. methodInvoked = (typeof query == 'string'),
  21. queryArguments = [].slice.call(arguments, 1),
  22. returnedValue
  23. ;
  24. $allModules
  25. .each(function() {
  26. var
  27. settings = $.extend(true, {}, $.fn.sticky.settings, parameters),
  28. className = settings.className,
  29. namespace = settings.namespace,
  30. error = settings.error,
  31. eventNamespace = '.' + namespace,
  32. moduleNamespace = 'module-' + namespace,
  33. $module = $(this),
  34. $window = $(window),
  35. $container = $module.offsetParent(),
  36. $scroll = $(settings.scrollContext),
  37. $context,
  38. selector = $module.selector || '',
  39. instance = $module.data(moduleNamespace),
  40. requestAnimationFrame = window.requestAnimationFrame
  41. || window.mozRequestAnimationFrame
  42. || window.webkitRequestAnimationFrame
  43. || window.msRequestAnimationFrame
  44. || function(callback) { setTimeout(callback, 0); },
  45. element = this,
  46. observer,
  47. module
  48. ;
  49. module = {
  50. initialize: function() {
  51. if(settings.context) {
  52. $context = $(settings.context);
  53. }
  54. else {
  55. $context = $container;
  56. }
  57. if($context.length === 0) {
  58. module.error(error.invalidContext, settings.context, $module);
  59. return;
  60. }
  61. module.verbose('Initializing sticky', settings, $container);
  62. module.save.positions();
  63. // error conditions
  64. if( module.is.hidden() ) {
  65. module.error(error.visible, $module);
  66. }
  67. if(module.cache.element.height > module.cache.context.height) {
  68. module.reset();
  69. module.error(error.elementSize, $module);
  70. return;
  71. }
  72. $window
  73. .on('resize' + eventNamespace, module.event.resize)
  74. ;
  75. $scroll
  76. .on('scroll' + eventNamespace, module.event.scroll)
  77. ;
  78. module.observeChanges();
  79. module.instantiate();
  80. },
  81. instantiate: function() {
  82. module.verbose('Storing instance of module', module);
  83. instance = module;
  84. $module
  85. .data(moduleNamespace, module)
  86. ;
  87. },
  88. destroy: function() {
  89. module.verbose('Destroying previous module');
  90. module.reset();
  91. if(observer) {
  92. observer.disconnect();
  93. }
  94. $window
  95. .off('resize' + eventNamespace, module.event.resize)
  96. ;
  97. $scroll
  98. .off('scroll' + eventNamespace, module.event.scroll)
  99. ;
  100. $module
  101. .removeData(moduleNamespace)
  102. ;
  103. },
  104. observeChanges: function() {
  105. var
  106. context = $context[0]
  107. ;
  108. if(settings.observeChanges) {
  109. if('MutationObserver' in window) {
  110. observer = new MutationObserver(function(mutations) {
  111. clearTimeout(module.timer);
  112. module.timer = setTimeout(function() {
  113. module.verbose('DOM tree modified, updating sticky menu');
  114. module.refresh();
  115. }, 200);
  116. });
  117. observer.observe(element, {
  118. childList : true,
  119. subtree : true
  120. });
  121. observer.observe(context, {
  122. childList : true,
  123. subtree : true
  124. });
  125. module.debug('Setting up mutation observer', observer);
  126. }
  127. }
  128. },
  129. event: {
  130. resize: function() {
  131. requestAnimationFrame(function() {
  132. module.refresh();
  133. module.stick();
  134. });
  135. },
  136. scroll: function() {
  137. requestAnimationFrame(function() {
  138. module.stick();
  139. settings.onScroll.call(element);
  140. });
  141. }
  142. },
  143. refresh: function(hardRefresh) {
  144. module.reset();
  145. if(hardRefresh) {
  146. $container = $module.offsetParent();
  147. }
  148. module.save.positions();
  149. module.stick();
  150. settings.onReposition.call(element);
  151. },
  152. supports: {
  153. sticky: function() {
  154. var
  155. $element = $('<div/>'),
  156. element = $element.get()
  157. ;
  158. $element
  159. .addClass(className.supported)
  160. ;
  161. return($element.css('position').match('sticky'));
  162. }
  163. },
  164. save: {
  165. scroll: function(scroll) {
  166. module.lastScroll = scroll;
  167. },
  168. positions: function() {
  169. var
  170. window = {
  171. height: $window.height()
  172. },
  173. element = {
  174. margin: {
  175. top : parseInt($module.css('margin-top'), 10),
  176. bottom : parseInt($module.css('margin-bottom'), 10),
  177. },
  178. offset : $module.offset(),
  179. width : $module.outerWidth(),
  180. height : $module.outerHeight()
  181. },
  182. context = {
  183. offset: $context.offset(),
  184. height: $context.outerHeight()
  185. }
  186. ;
  187. module.cache = {
  188. fits : ( element.height < window.height ),
  189. window: {
  190. height: window.height
  191. },
  192. element: {
  193. margin : element.margin,
  194. top : element.offset.top - element.margin.top,
  195. left : element.offset.left,
  196. width : element.width,
  197. height : element.height,
  198. bottom : element.offset.top + element.height
  199. },
  200. context: {
  201. top : context.offset.top,
  202. height : context.height,
  203. bottom : context.offset.top + context.height
  204. }
  205. };
  206. module.set.containerSize();
  207. module.set.size();
  208. module.stick();
  209. module.debug('Caching element positions', module.cache);
  210. }
  211. },
  212. get: {
  213. direction: function(scroll) {
  214. var
  215. direction = 'down'
  216. ;
  217. scroll = scroll || $scroll.scrollTop();
  218. if(module.lastScroll !== undefined) {
  219. if(module.lastScroll < scroll) {
  220. direction = 'down';
  221. }
  222. else if(module.lastScroll > scroll) {
  223. direction = 'up';
  224. }
  225. }
  226. return direction;
  227. },
  228. scrollChange: function(scroll) {
  229. scroll = scroll || $scroll.scrollTop();
  230. return (module.lastScroll)
  231. ? (scroll - module.lastScroll)
  232. : 0
  233. ;
  234. },
  235. currentElementScroll: function() {
  236. return ( module.is.top() )
  237. ? Math.abs(parseInt($module.css('top'), 10)) || 0
  238. : Math.abs(parseInt($module.css('bottom'), 10)) || 0
  239. ;
  240. },
  241. elementScroll: function(scroll) {
  242. scroll = scroll || $scroll.scrollTop();
  243. var
  244. element = module.cache.element,
  245. window = module.cache.window,
  246. delta = module.get.scrollChange(scroll),
  247. maxScroll = (element.height - window.height + settings.offset),
  248. currentScroll = module.get.currentElementScroll(),
  249. possibleScroll = (currentScroll + delta),
  250. elementScroll
  251. ;
  252. if(module.cache.fits || possibleScroll < 0) {
  253. elementScroll = 0;
  254. }
  255. else if (possibleScroll > maxScroll ) {
  256. elementScroll = maxScroll;
  257. }
  258. else {
  259. elementScroll = possibleScroll;
  260. }
  261. return elementScroll;
  262. }
  263. },
  264. remove: {
  265. offset: function() {
  266. $module.css('margin-top', '');
  267. }
  268. },
  269. set: {
  270. offset: function() {
  271. module.verbose('Setting offset on element', settings.offset);
  272. $module.css('margin-top', settings.offset);
  273. },
  274. containerSize: function() {
  275. var
  276. tagName = $container.get(0).tagName
  277. ;
  278. if(tagName === 'HTML' || tagName == 'body') {
  279. // this can trigger for too many reasons
  280. //module.error(error.container, tagName, $module);
  281. $container = $module.offsetParent();
  282. }
  283. else {
  284. module.debug('Settings container size', module.cache.context.height);
  285. $container.height(module.cache.context.height);
  286. }
  287. },
  288. scroll: function(scroll) {
  289. module.debug('Setting scroll on element', scroll);
  290. if( module.is.top() ) {
  291. $module
  292. .css('bottom', '')
  293. .css('top', -scroll)
  294. ;
  295. }
  296. if( module.is.bottom() ) {
  297. $module
  298. .css('top', '')
  299. .css('bottom', scroll)
  300. ;
  301. }
  302. },
  303. size: function() {
  304. if(module.cache.element.height !== 0 && module.cache.element.width !== 0) {
  305. $module
  306. .css({
  307. width : module.cache.element.width,
  308. height : module.cache.element.height
  309. })
  310. ;
  311. }
  312. }
  313. },
  314. is: {
  315. top: function() {
  316. return $module.hasClass(className.top);
  317. },
  318. bottom: function() {
  319. return $module.hasClass(className.bottom);
  320. },
  321. initialPosition: function() {
  322. return (!module.is.fixed() && !module.is.bound());
  323. },
  324. hidden: function() {
  325. return (!$module.is(':visible'));
  326. },
  327. bound: function() {
  328. return $module.hasClass(className.bound);
  329. },
  330. fixed: function() {
  331. return $module.hasClass(className.fixed);
  332. }
  333. },
  334. stick: function() {
  335. var
  336. cache = module.cache,
  337. fits = cache.fits,
  338. element = cache.element,
  339. window = cache.window,
  340. context = cache.context,
  341. offset = (module.is.bottom() && settings.pushing)
  342. ? settings.bottomOffset
  343. : settings.offset,
  344. scroll = {
  345. top : $scroll.scrollTop() + offset,
  346. bottom : $scroll.scrollTop() + offset + window.height
  347. },
  348. direction = module.get.direction(scroll.top),
  349. elementScroll = module.get.elementScroll(scroll.top),
  350. // shorthand
  351. doesntFit = !fits,
  352. elementVisible = (element.height !== 0)
  353. ;
  354. // save current scroll for next run
  355. module.save.scroll(scroll.top);
  356. if(elementVisible) {
  357. if( module.is.initialPosition() ) {
  358. if(scroll.top >= element.top) {
  359. module.debug('Element passed, fixing element to page');
  360. module.fixTop();
  361. }
  362. }
  363. else if( module.is.fixed() ) {
  364. // currently fixed top
  365. if( module.is.top() ) {
  366. if( scroll.top < element.top ) {
  367. module.debug('Fixed element reached top of container');
  368. module.setInitialPosition();
  369. }
  370. else if( (element.height + scroll.top - elementScroll) > context.bottom ) {
  371. module.debug('Fixed element reached bottom of container');
  372. module.bindBottom();
  373. }
  374. // scroll element if larger than screen
  375. else if(doesntFit) {
  376. module.set.scroll(elementScroll);
  377. }
  378. }
  379. // currently fixed bottom
  380. else if(module.is.bottom() ) {
  381. // top edge
  382. if( (scroll.bottom - element.height) < element.top) {
  383. module.debug('Bottom fixed rail has reached top of container');
  384. module.setInitialPosition();
  385. }
  386. // bottom edge
  387. else if(scroll.bottom > context.bottom) {
  388. module.debug('Bottom fixed rail has reached bottom of container');
  389. module.bindBottom();
  390. }
  391. // scroll element if larger than screen
  392. else if(doesntFit) {
  393. module.set.scroll(elementScroll);
  394. }
  395. }
  396. }
  397. else if( module.is.bottom() ) {
  398. if(settings.pushing) {
  399. if(module.is.bound() && scroll.bottom < context.bottom ) {
  400. module.debug('Fixing bottom attached element to bottom of browser.');
  401. module.fixBottom();
  402. }
  403. }
  404. else {
  405. if(module.is.bound() && (scroll.top < context.bottom - element.height) ) {
  406. module.debug('Fixing bottom attached element to top of browser.');
  407. module.fixTop();
  408. }
  409. }
  410. }
  411. }
  412. },
  413. bindTop: function() {
  414. module.debug('Binding element to top of parent container');
  415. module.remove.offset();
  416. $module
  417. .css('left' , '')
  418. .css('top' , '')
  419. .css('bottom' , '')
  420. .removeClass(className.fixed)
  421. .removeClass(className.bottom)
  422. .addClass(className.bound)
  423. .addClass(className.top)
  424. ;
  425. settings.onTop.call(element);
  426. settings.onUnstick.call(element);
  427. },
  428. bindBottom: function() {
  429. module.debug('Binding element to bottom of parent container');
  430. module.remove.offset();
  431. $module
  432. .css('left' , '')
  433. .css('top' , '')
  434. .css('bottom' , '')
  435. .removeClass(className.fixed)
  436. .removeClass(className.top)
  437. .addClass(className.bound)
  438. .addClass(className.bottom)
  439. ;
  440. settings.onBottom.call(element);
  441. settings.onUnstick.call(element);
  442. },
  443. setInitialPosition: function() {
  444. module.unfix();
  445. module.unbind();
  446. },
  447. fixTop: function() {
  448. module.debug('Fixing element to top of page');
  449. module.set.offset();
  450. $module
  451. .css('left', module.cache.element.left)
  452. .removeClass(className.bound)
  453. .removeClass(className.bottom)
  454. .addClass(className.fixed)
  455. .addClass(className.top)
  456. ;
  457. settings.onStick.call(element);
  458. },
  459. fixBottom: function() {
  460. module.debug('Sticking element to bottom of page');
  461. module.set.offset();
  462. $module
  463. .css('left', module.cache.element.left)
  464. .removeClass(className.bound)
  465. .removeClass(className.top)
  466. .addClass(className.fixed)
  467. .addClass(className.bottom)
  468. ;
  469. settings.onStick.call(element);
  470. },
  471. unbind: function() {
  472. module.debug('Removing absolute position on element');
  473. module.remove.offset();
  474. $module
  475. .removeClass(className.bound)
  476. .removeClass(className.top)
  477. .removeClass(className.bottom)
  478. ;
  479. },
  480. unfix: function() {
  481. module.debug('Removing fixed position on element');
  482. module.remove.offset();
  483. $module
  484. .removeClass(className.fixed)
  485. .removeClass(className.top)
  486. .removeClass(className.bottom)
  487. ;
  488. settings.onUnstick.call(element);
  489. },
  490. reset: function() {
  491. module.debug('Reseting elements position');
  492. module.unbind();
  493. module.unfix();
  494. module.resetCSS();
  495. },
  496. resetCSS: function() {
  497. $module
  498. .css({
  499. top : '',
  500. bottom : '',
  501. width : '',
  502. height : ''
  503. })
  504. ;
  505. $container
  506. .css({
  507. height: ''
  508. })
  509. ;
  510. },
  511. setting: function(name, value) {
  512. if( $.isPlainObject(name) ) {
  513. $.extend(true, settings, name);
  514. }
  515. else if(value !== undefined) {
  516. settings[name] = value;
  517. }
  518. else {
  519. return settings[name];
  520. }
  521. },
  522. internal: function(name, value) {
  523. if( $.isPlainObject(name) ) {
  524. $.extend(true, module, name);
  525. }
  526. else if(value !== undefined) {
  527. module[name] = value;
  528. }
  529. else {
  530. return module[name];
  531. }
  532. },
  533. debug: function() {
  534. if(settings.debug) {
  535. if(settings.performance) {
  536. module.performance.log(arguments);
  537. }
  538. else {
  539. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  540. module.debug.apply(console, arguments);
  541. }
  542. }
  543. },
  544. verbose: function() {
  545. if(settings.verbose && settings.debug) {
  546. if(settings.performance) {
  547. module.performance.log(arguments);
  548. }
  549. else {
  550. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  551. module.verbose.apply(console, arguments);
  552. }
  553. }
  554. },
  555. error: function() {
  556. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  557. module.error.apply(console, arguments);
  558. },
  559. performance: {
  560. log: function(message) {
  561. var
  562. currentTime,
  563. executionTime,
  564. previousTime
  565. ;
  566. if(settings.performance) {
  567. currentTime = new Date().getTime();
  568. previousTime = time || currentTime;
  569. executionTime = currentTime - previousTime;
  570. time = currentTime;
  571. performance.push({
  572. 'Name' : message[0],
  573. 'Arguments' : [].slice.call(message, 1) || '',
  574. 'Element' : element,
  575. 'Execution Time' : executionTime
  576. });
  577. }
  578. clearTimeout(module.performance.timer);
  579. module.performance.timer = setTimeout(module.performance.display, 0);
  580. },
  581. display: function() {
  582. var
  583. title = settings.name + ':',
  584. totalTime = 0
  585. ;
  586. time = false;
  587. clearTimeout(module.performance.timer);
  588. $.each(performance, function(index, data) {
  589. totalTime += data['Execution Time'];
  590. });
  591. title += ' ' + totalTime + 'ms';
  592. if(moduleSelector) {
  593. title += ' \'' + moduleSelector + '\'';
  594. }
  595. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  596. console.groupCollapsed(title);
  597. if(console.table) {
  598. console.table(performance);
  599. }
  600. else {
  601. $.each(performance, function(index, data) {
  602. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  603. });
  604. }
  605. console.groupEnd();
  606. }
  607. performance = [];
  608. }
  609. },
  610. invoke: function(query, passedArguments, context) {
  611. var
  612. object = instance,
  613. maxDepth,
  614. found,
  615. response
  616. ;
  617. passedArguments = passedArguments || queryArguments;
  618. context = element || context;
  619. if(typeof query == 'string' && object !== undefined) {
  620. query = query.split(/[\. ]/);
  621. maxDepth = query.length - 1;
  622. $.each(query, function(depth, value) {
  623. var camelCaseValue = (depth != maxDepth)
  624. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  625. : query
  626. ;
  627. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  628. object = object[camelCaseValue];
  629. }
  630. else if( object[camelCaseValue] !== undefined ) {
  631. found = object[camelCaseValue];
  632. return false;
  633. }
  634. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  635. object = object[value];
  636. }
  637. else if( object[value] !== undefined ) {
  638. found = object[value];
  639. return false;
  640. }
  641. else {
  642. return false;
  643. }
  644. });
  645. }
  646. if ( $.isFunction( found ) ) {
  647. response = found.apply(context, passedArguments);
  648. }
  649. else if(found !== undefined) {
  650. response = found;
  651. }
  652. if($.isArray(returnedValue)) {
  653. returnedValue.push(response);
  654. }
  655. else if(returnedValue !== undefined) {
  656. returnedValue = [returnedValue, response];
  657. }
  658. else if(response !== undefined) {
  659. returnedValue = response;
  660. }
  661. return found;
  662. }
  663. };
  664. if(methodInvoked) {
  665. if(instance === undefined) {
  666. module.initialize();
  667. }
  668. module.invoke(query);
  669. }
  670. else {
  671. if(instance !== undefined) {
  672. module.destroy();
  673. }
  674. module.initialize();
  675. }
  676. })
  677. ;
  678. return (returnedValue !== undefined)
  679. ? returnedValue
  680. : this
  681. ;
  682. };
  683. $.fn.sticky.settings = {
  684. name : 'Sticky',
  685. namespace : 'sticky',
  686. debug : false,
  687. verbose : false,
  688. performance : false,
  689. pushing : false,
  690. context : false,
  691. scrollContext : window,
  692. offset : 0,
  693. bottomOffset : 0,
  694. observeChanges : true,
  695. onReposition : function(){},
  696. onScroll : function(){},
  697. onStick : function(){},
  698. onUnstick : function(){},
  699. onTop : function(){},
  700. onBottom : function(){},
  701. error : {
  702. container : 'Sticky element must be inside a relative container',
  703. visible : 'Element is hidden, you must call refresh after element becomes visible',
  704. method : 'The method you called is not defined.',
  705. invalidContext : 'Context specified does not exist',
  706. elementSize : 'Sticky element is larger than its container, cannot create sticky.'
  707. },
  708. className : {
  709. bound : 'bound',
  710. fixed : 'fixed',
  711. supported : 'native',
  712. top : 'top',
  713. bottom : 'bottom'
  714. }
  715. };
  716. })( jQuery, window , document );