accordion.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. /*!
  2. * # Fomantic-UI - Accordion
  3. * http://github.com/fomantic/Fomantic-UI/
  4. *
  5. *
  6. * Released under the MIT license
  7. * http://opensource.org/licenses/MIT
  8. *
  9. */
  10. ;(function ($, window, document, undefined) {
  11. 'use strict';
  12. $.isFunction = $.isFunction || function(obj) {
  13. return typeof obj === "function" && typeof obj.nodeType !== "number";
  14. };
  15. window = (typeof window != 'undefined' && window.Math == Math)
  16. ? window
  17. : (typeof self != 'undefined' && self.Math == Math)
  18. ? self
  19. : Function('return this')()
  20. ;
  21. $.fn.accordion = function(parameters) {
  22. var
  23. $allModules = $(this),
  24. time = new Date().getTime(),
  25. performance = [],
  26. query = arguments[0],
  27. methodInvoked = (typeof query == 'string'),
  28. queryArguments = [].slice.call(arguments, 1),
  29. returnedValue
  30. ;
  31. $allModules
  32. .each(function() {
  33. var
  34. settings = ( $.isPlainObject(parameters) )
  35. ? $.extend(true, {}, $.fn.accordion.settings, parameters)
  36. : $.extend({}, $.fn.accordion.settings),
  37. className = settings.className,
  38. namespace = settings.namespace,
  39. selector = settings.selector,
  40. error = settings.error,
  41. eventNamespace = '.' + namespace,
  42. moduleNamespace = 'module-' + namespace,
  43. moduleSelector = $allModules.selector || '',
  44. $module = $(this),
  45. $title = $module.find(selector.title),
  46. $content = $module.find(selector.content),
  47. element = this,
  48. instance = $module.data(moduleNamespace),
  49. observer,
  50. module
  51. ;
  52. module = {
  53. initialize: function() {
  54. module.debug('Initializing', $module);
  55. module.bind.events();
  56. if(settings.observeChanges) {
  57. module.observeChanges();
  58. }
  59. module.instantiate();
  60. },
  61. instantiate: function() {
  62. instance = module;
  63. $module
  64. .data(moduleNamespace, module)
  65. ;
  66. },
  67. destroy: function() {
  68. module.debug('Destroying previous instance', $module);
  69. $module
  70. .off(eventNamespace)
  71. .removeData(moduleNamespace)
  72. ;
  73. },
  74. refresh: function() {
  75. $title = $module.find(selector.title);
  76. $content = $module.find(selector.content);
  77. },
  78. observeChanges: function() {
  79. if('MutationObserver' in window) {
  80. observer = new MutationObserver(function(mutations) {
  81. module.debug('DOM tree modified, updating selector cache');
  82. module.refresh();
  83. });
  84. observer.observe(element, {
  85. childList : true,
  86. subtree : true
  87. });
  88. module.debug('Setting up mutation observer', observer);
  89. }
  90. },
  91. bind: {
  92. events: function() {
  93. module.debug('Binding delegated events');
  94. $module
  95. .on(settings.on + eventNamespace, selector.trigger, module.event.click)
  96. ;
  97. }
  98. },
  99. event: {
  100. click: function() {
  101. module.toggle.call(this);
  102. }
  103. },
  104. toggle: function(query) {
  105. var
  106. $activeTitle = (query !== undefined)
  107. ? (typeof query === 'number')
  108. ? $title.eq(query)
  109. : $(query).closest(selector.title)
  110. : $(this).closest(selector.title),
  111. $activeContent = $activeTitle.next($content),
  112. isAnimating = $activeContent.hasClass(className.animating),
  113. isActive = $activeContent.hasClass(className.active),
  114. isOpen = (isActive && !isAnimating),
  115. isOpening = (!isActive && isAnimating)
  116. ;
  117. module.debug('Toggling visibility of content', $activeTitle);
  118. if(isOpen || isOpening) {
  119. if(settings.collapsible) {
  120. module.close.call($activeTitle);
  121. }
  122. else {
  123. module.debug('Cannot close accordion content collapsing is disabled');
  124. }
  125. }
  126. else {
  127. module.open.call($activeTitle);
  128. }
  129. },
  130. open: function(query) {
  131. var
  132. $activeTitle = (query !== undefined)
  133. ? (typeof query === 'number')
  134. ? $title.eq(query)
  135. : $(query).closest(selector.title)
  136. : $(this).closest(selector.title),
  137. $activeContent = $activeTitle.next($content),
  138. isAnimating = $activeContent.hasClass(className.animating),
  139. isActive = $activeContent.hasClass(className.active),
  140. isOpen = (isActive || isAnimating)
  141. ;
  142. if(isOpen) {
  143. module.debug('Accordion already open, skipping', $activeContent);
  144. return;
  145. }
  146. module.debug('Opening accordion content', $activeTitle);
  147. settings.onOpening.call($activeContent);
  148. settings.onChanging.call($activeContent);
  149. if(settings.exclusive) {
  150. module.closeOthers.call($activeTitle);
  151. }
  152. $activeTitle
  153. .addClass(className.active)
  154. ;
  155. $activeContent
  156. .stop(true, true)
  157. .addClass(className.animating)
  158. ;
  159. if(settings.animateChildren) {
  160. if($.fn.transition !== undefined && $module.transition('is supported')) {
  161. $activeContent
  162. .children()
  163. .transition({
  164. animation : 'fade in',
  165. queue : false,
  166. useFailSafe : true,
  167. debug : settings.debug,
  168. verbose : settings.verbose,
  169. duration : settings.duration,
  170. skipInlineHidden : true,
  171. onComplete: function() {
  172. $activeContent.children().removeClass(className.transition);
  173. }
  174. })
  175. ;
  176. }
  177. else {
  178. $activeContent
  179. .children()
  180. .stop(true, true)
  181. .animate({
  182. opacity: 1
  183. }, settings.duration, module.resetOpacity)
  184. ;
  185. }
  186. }
  187. $activeContent
  188. .slideDown(settings.duration, settings.easing, function() {
  189. $activeContent
  190. .removeClass(className.animating)
  191. .addClass(className.active)
  192. ;
  193. module.reset.display.call(this);
  194. settings.onOpen.call(this);
  195. settings.onChange.call(this);
  196. })
  197. ;
  198. },
  199. close: function(query) {
  200. var
  201. $activeTitle = (query !== undefined)
  202. ? (typeof query === 'number')
  203. ? $title.eq(query)
  204. : $(query).closest(selector.title)
  205. : $(this).closest(selector.title),
  206. $activeContent = $activeTitle.next($content),
  207. isAnimating = $activeContent.hasClass(className.animating),
  208. isActive = $activeContent.hasClass(className.active),
  209. isOpening = (!isActive && isAnimating),
  210. isClosing = (isActive && isAnimating)
  211. ;
  212. if((isActive || isOpening) && !isClosing) {
  213. module.debug('Closing accordion content', $activeContent);
  214. settings.onClosing.call($activeContent);
  215. settings.onChanging.call($activeContent);
  216. $activeTitle
  217. .removeClass(className.active)
  218. ;
  219. $activeContent
  220. .stop(true, true)
  221. .addClass(className.animating)
  222. ;
  223. if(settings.animateChildren) {
  224. if($.fn.transition !== undefined && $module.transition('is supported')) {
  225. $activeContent
  226. .children()
  227. .transition({
  228. animation : 'fade out',
  229. queue : false,
  230. useFailSafe : true,
  231. debug : settings.debug,
  232. verbose : settings.verbose,
  233. duration : settings.duration,
  234. skipInlineHidden : true
  235. })
  236. ;
  237. }
  238. else {
  239. $activeContent
  240. .children()
  241. .stop(true, true)
  242. .animate({
  243. opacity: 0
  244. }, settings.duration, module.resetOpacity)
  245. ;
  246. }
  247. }
  248. $activeContent
  249. .slideUp(settings.duration, settings.easing, function() {
  250. $activeContent
  251. .removeClass(className.animating)
  252. .removeClass(className.active)
  253. ;
  254. module.reset.display.call(this);
  255. settings.onClose.call(this);
  256. settings.onChange.call(this);
  257. })
  258. ;
  259. }
  260. },
  261. closeOthers: function(index) {
  262. var
  263. $activeTitle = (index !== undefined)
  264. ? $title.eq(index)
  265. : $(this).closest(selector.title),
  266. $parentTitles = $activeTitle.parents(selector.content).prev(selector.title),
  267. $activeAccordion = $activeTitle.closest(selector.accordion),
  268. activeSelector = selector.title + '.' + className.active + ':visible',
  269. activeContent = selector.content + '.' + className.active + ':visible',
  270. $openTitles,
  271. $nestedTitles,
  272. $openContents
  273. ;
  274. if(settings.closeNested) {
  275. $openTitles = $activeAccordion.find(activeSelector).not($parentTitles);
  276. $openContents = $openTitles.next($content);
  277. }
  278. else {
  279. $openTitles = $activeAccordion.find(activeSelector).not($parentTitles);
  280. $nestedTitles = $activeAccordion.find(activeContent).find(activeSelector).not($parentTitles);
  281. $openTitles = $openTitles.not($nestedTitles);
  282. $openContents = $openTitles.next($content);
  283. }
  284. if( ($openTitles.length > 0) ) {
  285. module.debug('Exclusive enabled, closing other content', $openTitles);
  286. $openTitles
  287. .removeClass(className.active)
  288. ;
  289. $openContents
  290. .removeClass(className.animating)
  291. .stop(true, true)
  292. ;
  293. if(settings.animateChildren) {
  294. if($.fn.transition !== undefined && $module.transition('is supported')) {
  295. $openContents
  296. .children()
  297. .transition({
  298. animation : 'fade out',
  299. useFailSafe : true,
  300. debug : settings.debug,
  301. verbose : settings.verbose,
  302. duration : settings.duration,
  303. skipInlineHidden : true
  304. })
  305. ;
  306. }
  307. else {
  308. $openContents
  309. .children()
  310. .stop(true, true)
  311. .animate({
  312. opacity: 0
  313. }, settings.duration, module.resetOpacity)
  314. ;
  315. }
  316. }
  317. $openContents
  318. .slideUp(settings.duration , settings.easing, function() {
  319. $(this).removeClass(className.active);
  320. module.reset.display.call(this);
  321. })
  322. ;
  323. }
  324. },
  325. reset: {
  326. display: function() {
  327. module.verbose('Removing inline display from element', this);
  328. $(this).css('display', '');
  329. if( $(this).attr('style') === '') {
  330. $(this)
  331. .attr('style', '')
  332. .removeAttr('style')
  333. ;
  334. }
  335. },
  336. opacity: function() {
  337. module.verbose('Removing inline opacity from element', this);
  338. $(this).css('opacity', '');
  339. if( $(this).attr('style') === '') {
  340. $(this)
  341. .attr('style', '')
  342. .removeAttr('style')
  343. ;
  344. }
  345. },
  346. },
  347. setting: function(name, value) {
  348. module.debug('Changing setting', name, value);
  349. if( $.isPlainObject(name) ) {
  350. $.extend(true, settings, name);
  351. }
  352. else if(value !== undefined) {
  353. if($.isPlainObject(settings[name])) {
  354. $.extend(true, settings[name], value);
  355. }
  356. else {
  357. settings[name] = value;
  358. }
  359. }
  360. else {
  361. return settings[name];
  362. }
  363. },
  364. internal: function(name, value) {
  365. module.debug('Changing internal', name, value);
  366. if(value !== undefined) {
  367. if( $.isPlainObject(name) ) {
  368. $.extend(true, module, name);
  369. }
  370. else {
  371. module[name] = value;
  372. }
  373. }
  374. else {
  375. return module[name];
  376. }
  377. },
  378. debug: function() {
  379. if(!settings.silent && settings.debug) {
  380. if(settings.performance) {
  381. module.performance.log(arguments);
  382. }
  383. else {
  384. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  385. module.debug.apply(console, arguments);
  386. }
  387. }
  388. },
  389. verbose: function() {
  390. if(!settings.silent && settings.verbose && settings.debug) {
  391. if(settings.performance) {
  392. module.performance.log(arguments);
  393. }
  394. else {
  395. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  396. module.verbose.apply(console, arguments);
  397. }
  398. }
  399. },
  400. error: function() {
  401. if(!settings.silent) {
  402. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  403. module.error.apply(console, arguments);
  404. }
  405. },
  406. performance: {
  407. log: function(message) {
  408. var
  409. currentTime,
  410. executionTime,
  411. previousTime
  412. ;
  413. if(settings.performance) {
  414. currentTime = new Date().getTime();
  415. previousTime = time || currentTime;
  416. executionTime = currentTime - previousTime;
  417. time = currentTime;
  418. performance.push({
  419. 'Name' : message[0],
  420. 'Arguments' : [].slice.call(message, 1) || '',
  421. 'Element' : element,
  422. 'Execution Time' : executionTime
  423. });
  424. }
  425. clearTimeout(module.performance.timer);
  426. module.performance.timer = setTimeout(module.performance.display, 500);
  427. },
  428. display: function() {
  429. var
  430. title = settings.name + ':',
  431. totalTime = 0
  432. ;
  433. time = false;
  434. clearTimeout(module.performance.timer);
  435. $.each(performance, function(index, data) {
  436. totalTime += data['Execution Time'];
  437. });
  438. title += ' ' + totalTime + 'ms';
  439. if(moduleSelector) {
  440. title += ' \'' + moduleSelector + '\'';
  441. }
  442. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  443. console.groupCollapsed(title);
  444. if(console.table) {
  445. console.table(performance);
  446. }
  447. else {
  448. $.each(performance, function(index, data) {
  449. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  450. });
  451. }
  452. console.groupEnd();
  453. }
  454. performance = [];
  455. }
  456. },
  457. invoke: function(query, passedArguments, context) {
  458. var
  459. object = instance,
  460. maxDepth,
  461. found,
  462. response
  463. ;
  464. passedArguments = passedArguments || queryArguments;
  465. context = element || context;
  466. if(typeof query == 'string' && object !== undefined) {
  467. query = query.split(/[\. ]/);
  468. maxDepth = query.length - 1;
  469. $.each(query, function(depth, value) {
  470. var camelCaseValue = (depth != maxDepth)
  471. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  472. : query
  473. ;
  474. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  475. object = object[camelCaseValue];
  476. }
  477. else if( object[camelCaseValue] !== undefined ) {
  478. found = object[camelCaseValue];
  479. return false;
  480. }
  481. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  482. object = object[value];
  483. }
  484. else if( object[value] !== undefined ) {
  485. found = object[value];
  486. return false;
  487. }
  488. else {
  489. module.error(error.method, query);
  490. return false;
  491. }
  492. });
  493. }
  494. if ( $.isFunction( found ) ) {
  495. response = found.apply(context, passedArguments);
  496. }
  497. else if(found !== undefined) {
  498. response = found;
  499. }
  500. if(Array.isArray(returnedValue)) {
  501. returnedValue.push(response);
  502. }
  503. else if(returnedValue !== undefined) {
  504. returnedValue = [returnedValue, response];
  505. }
  506. else if(response !== undefined) {
  507. returnedValue = response;
  508. }
  509. return found;
  510. }
  511. };
  512. if(methodInvoked) {
  513. if(instance === undefined) {
  514. module.initialize();
  515. }
  516. module.invoke(query);
  517. }
  518. else {
  519. if(instance !== undefined) {
  520. instance.invoke('destroy');
  521. }
  522. module.initialize();
  523. }
  524. })
  525. ;
  526. return (returnedValue !== undefined)
  527. ? returnedValue
  528. : this
  529. ;
  530. };
  531. $.fn.accordion.settings = {
  532. name : 'Accordion',
  533. namespace : 'accordion',
  534. silent : false,
  535. debug : false,
  536. verbose : false,
  537. performance : true,
  538. on : 'click', // event on title that opens accordion
  539. observeChanges : true, // whether accordion should automatically refresh on DOM insertion
  540. exclusive : true, // whether a single accordion content panel should be open at once
  541. collapsible : true, // whether accordion content can be closed
  542. closeNested : false, // whether nested content should be closed when a panel is closed
  543. animateChildren : true, // whether children opacity should be animated
  544. duration : 350, // duration of animation
  545. easing : 'easeOutQuad', // easing equation for animation
  546. onOpening : function(){}, // callback before open animation
  547. onClosing : function(){}, // callback before closing animation
  548. onChanging : function(){}, // callback before closing or opening animation
  549. onOpen : function(){}, // callback after open animation
  550. onClose : function(){}, // callback after closing animation
  551. onChange : function(){}, // callback after closing or opening animation
  552. error: {
  553. method : 'The method you called is not defined'
  554. },
  555. className : {
  556. active : 'active',
  557. animating : 'animating',
  558. transition: 'transition'
  559. },
  560. selector : {
  561. accordion : '.accordion',
  562. title : '.title',
  563. trigger : '.title',
  564. content : '.content'
  565. }
  566. };
  567. // Adds easing
  568. $.extend( $.easing, {
  569. easeOutQuad: function (x, t, b, c, d) {
  570. return -c *(t/=d)*(t-2) + b;
  571. }
  572. });
  573. })( jQuery, window, document );