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.

766 lines
23 KiB

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