foundation.tabs.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. 'use strict';
  2. import $ from 'jquery';
  3. import { onLoad } from './foundation.core.utils';
  4. import { Keyboard } from './foundation.util.keyboard';
  5. import { onImagesLoaded } from './foundation.util.imageLoader';
  6. import { Plugin } from './foundation.core.plugin';
  7. /**
  8. * Tabs module.
  9. * @module foundation.tabs
  10. * @requires foundation.util.keyboard
  11. * @requires foundation.util.imageLoader if tabs contain images
  12. */
  13. class Tabs extends Plugin {
  14. /**
  15. * Creates a new instance of tabs.
  16. * @class
  17. * @name Tabs
  18. * @fires Tabs#init
  19. * @param {jQuery} element - jQuery object to make into tabs.
  20. * @param {Object} options - Overrides to the default plugin settings.
  21. */
  22. _setup(element, options) {
  23. this.$element = element;
  24. this.options = $.extend({}, Tabs.defaults, this.$element.data(), options);
  25. this.className = 'Tabs'; // ie9 back compat
  26. this._init();
  27. Keyboard.register('Tabs', {
  28. 'ENTER': 'open',
  29. 'SPACE': 'open',
  30. 'ARROW_RIGHT': 'next',
  31. 'ARROW_UP': 'previous',
  32. 'ARROW_DOWN': 'next',
  33. 'ARROW_LEFT': 'previous'
  34. // 'TAB': 'next',
  35. // 'SHIFT_TAB': 'previous'
  36. });
  37. }
  38. /**
  39. * Initializes the tabs by showing and focusing (if autoFocus=true) the preset active tab.
  40. * @private
  41. */
  42. _init() {
  43. var _this = this;
  44. this._isInitializing = true;
  45. this.$element.attr({'role': 'tablist'});
  46. this.$tabTitles = this.$element.find(`.${this.options.linkClass}`);
  47. this.$tabContent = $(`[data-tabs-content="${this.$element[0].id}"]`);
  48. this.$tabTitles.each(function(){
  49. var $elem = $(this),
  50. $link = $elem.find('a'),
  51. isActive = $elem.hasClass(`${_this.options.linkActiveClass}`),
  52. hash = $link.attr('data-tabs-target') || $link[0].hash.slice(1),
  53. linkId = $link[0].id ? $link[0].id : `${hash}-label`,
  54. $tabContent = $(`#${hash}`);
  55. $elem.attr({'role': 'presentation'});
  56. $link.attr({
  57. 'role': 'tab',
  58. 'aria-controls': hash,
  59. 'aria-selected': isActive,
  60. 'id': linkId,
  61. 'tabindex': isActive ? '0' : '-1'
  62. });
  63. $tabContent.attr({
  64. 'role': 'tabpanel',
  65. 'aria-labelledby': linkId
  66. });
  67. // Save up the initial hash to return to it later when going back in history
  68. if (isActive) {
  69. _this._initialAnchor = `#${hash}`;
  70. }
  71. if(!isActive) {
  72. $tabContent.attr('aria-hidden', 'true');
  73. }
  74. if(isActive && _this.options.autoFocus){
  75. _this.onLoadListener = onLoad($(window), function() {
  76. $('html, body').animate({ scrollTop: $elem.offset().top }, _this.options.deepLinkSmudgeDelay, () => {
  77. $link.focus();
  78. });
  79. });
  80. }
  81. });
  82. if(this.options.matchHeight) {
  83. var $images = this.$tabContent.find('img');
  84. if ($images.length) {
  85. onImagesLoaded($images, this._setHeight.bind(this));
  86. } else {
  87. this._setHeight();
  88. }
  89. }
  90. // Current context-bound function to open tabs on page load or history hashchange
  91. this._checkDeepLink = () => {
  92. var anchor = window.location.hash;
  93. if (!anchor.length) {
  94. // If we are still initializing and there is no anchor, then there is nothing to do
  95. if (this._isInitializing) return;
  96. // Otherwise, move to the initial anchor
  97. if (this._initialAnchor) anchor = this._initialAnchor;
  98. }
  99. var $anchor = anchor && $(anchor);
  100. var $link = anchor && this.$element.find('[href$="'+anchor+'"]');
  101. // Whether the anchor element that has been found is part of this element
  102. var isOwnAnchor = !!($anchor.length && $link.length);
  103. // If there is an anchor for the hash, select it
  104. if ($anchor && $anchor.length && $link && $link.length) {
  105. this.selectTab($anchor, true);
  106. }
  107. // Otherwise, collapse everything
  108. else {
  109. this._collapse();
  110. }
  111. if (isOwnAnchor) {
  112. // Roll up a little to show the titles
  113. if (this.options.deepLinkSmudge) {
  114. var offset = this.$element.offset();
  115. $('html, body').animate({ scrollTop: offset.top }, this.options.deepLinkSmudgeDelay);
  116. }
  117. /**
  118. * Fires when the plugin has deeplinked at pageload
  119. * @event Tabs#deeplink
  120. */
  121. this.$element.trigger('deeplink.zf.tabs', [$link, $anchor]);
  122. }
  123. }
  124. //use browser to open a tab, if it exists in this tabset
  125. if (this.options.deepLink) {
  126. this._checkDeepLink();
  127. }
  128. this._events();
  129. this._isInitializing = false;
  130. }
  131. /**
  132. * Adds event handlers for items within the tabs.
  133. * @private
  134. */
  135. _events() {
  136. this._addKeyHandler();
  137. this._addClickHandler();
  138. this._setHeightMqHandler = null;
  139. if (this.options.matchHeight) {
  140. this._setHeightMqHandler = this._setHeight.bind(this);
  141. $(window).on('changed.zf.mediaquery', this._setHeightMqHandler);
  142. }
  143. if(this.options.deepLink) {
  144. $(window).on('hashchange', this._checkDeepLink);
  145. }
  146. }
  147. /**
  148. * Adds click handlers for items within the tabs.
  149. * @private
  150. */
  151. _addClickHandler() {
  152. var _this = this;
  153. this.$element
  154. .off('click.zf.tabs')
  155. .on('click.zf.tabs', `.${this.options.linkClass}`, function(e){
  156. e.preventDefault();
  157. e.stopPropagation();
  158. _this._handleTabChange($(this));
  159. });
  160. }
  161. /**
  162. * Adds keyboard event handlers for items within the tabs.
  163. * @private
  164. */
  165. _addKeyHandler() {
  166. var _this = this;
  167. this.$tabTitles.off('keydown.zf.tabs').on('keydown.zf.tabs', function(e){
  168. if (e.which === 9) return;
  169. var $element = $(this),
  170. $elements = $element.parent('ul').children('li'),
  171. $prevElement,
  172. $nextElement;
  173. $elements.each(function(i) {
  174. if ($(this).is($element)) {
  175. if (_this.options.wrapOnKeys) {
  176. $prevElement = i === 0 ? $elements.last() : $elements.eq(i-1);
  177. $nextElement = i === $elements.length -1 ? $elements.first() : $elements.eq(i+1);
  178. } else {
  179. $prevElement = $elements.eq(Math.max(0, i-1));
  180. $nextElement = $elements.eq(Math.min(i+1, $elements.length-1));
  181. }
  182. return;
  183. }
  184. });
  185. // handle keyboard event with keyboard util
  186. Keyboard.handleKey(e, 'Tabs', {
  187. open: function() {
  188. $element.find('[role="tab"]').focus();
  189. _this._handleTabChange($element);
  190. },
  191. previous: function() {
  192. $prevElement.find('[role="tab"]').focus();
  193. _this._handleTabChange($prevElement);
  194. },
  195. next: function() {
  196. $nextElement.find('[role="tab"]').focus();
  197. _this._handleTabChange($nextElement);
  198. },
  199. handled: function() {
  200. e.stopPropagation();
  201. e.preventDefault();
  202. }
  203. });
  204. });
  205. }
  206. /**
  207. * Opens the tab `$targetContent` defined by `$target`. Collapses active tab.
  208. * @param {jQuery} $target - Tab to open.
  209. * @param {boolean} historyHandled - browser has already handled a history update
  210. * @fires Tabs#change
  211. * @function
  212. */
  213. _handleTabChange($target, historyHandled) {
  214. // With `activeCollapse`, if the target is the active Tab, collapse it.
  215. if ($target.hasClass(`${this.options.linkActiveClass}`)) {
  216. if(this.options.activeCollapse) {
  217. this._collapse();
  218. }
  219. return;
  220. }
  221. var $oldTab = this.$element.
  222. find(`.${this.options.linkClass}.${this.options.linkActiveClass}`),
  223. $tabLink = $target.find('[role="tab"]'),
  224. target = $tabLink.attr('data-tabs-target'),
  225. anchor = target && target.length ? `#${target}` : $tabLink[0].hash,
  226. $targetContent = this.$tabContent.find(anchor);
  227. //close old tab
  228. this._collapseTab($oldTab);
  229. //open new tab
  230. this._openTab($target);
  231. //either replace or update browser history
  232. if (this.options.deepLink && !historyHandled) {
  233. if (this.options.updateHistory) {
  234. history.pushState({}, '', anchor);
  235. } else {
  236. history.replaceState({}, '', anchor);
  237. }
  238. }
  239. /**
  240. * Fires when the plugin has successfully changed tabs.
  241. * @event Tabs#change
  242. */
  243. this.$element.trigger('change.zf.tabs', [$target, $targetContent]);
  244. //fire to children a mutation event
  245. $targetContent.find("[data-mutate]").trigger("mutateme.zf.trigger");
  246. }
  247. /**
  248. * Opens the tab `$targetContent` defined by `$target`.
  249. * @param {jQuery} $target - Tab to open.
  250. * @function
  251. */
  252. _openTab($target) {
  253. var $tabLink = $target.find('[role="tab"]'),
  254. hash = $tabLink.attr('data-tabs-target') || $tabLink[0].hash.slice(1),
  255. $targetContent = this.$tabContent.find(`#${hash}`);
  256. $target.addClass(`${this.options.linkActiveClass}`);
  257. $tabLink.attr({
  258. 'aria-selected': 'true',
  259. 'tabindex': '0'
  260. });
  261. $targetContent
  262. .addClass(`${this.options.panelActiveClass}`).removeAttr('aria-hidden');
  263. }
  264. /**
  265. * Collapses `$targetContent` defined by `$target`.
  266. * @param {jQuery} $target - Tab to collapse.
  267. * @function
  268. */
  269. _collapseTab($target) {
  270. var $target_anchor = $target
  271. .removeClass(`${this.options.linkActiveClass}`)
  272. .find('[role="tab"]')
  273. .attr({
  274. 'aria-selected': 'false',
  275. 'tabindex': -1
  276. });
  277. $(`#${$target_anchor.attr('aria-controls')}`)
  278. .removeClass(`${this.options.panelActiveClass}`)
  279. .attr({ 'aria-hidden': 'true' })
  280. }
  281. /**
  282. * Collapses the active Tab.
  283. * @fires Tabs#collapse
  284. * @function
  285. */
  286. _collapse() {
  287. var $activeTab = this.$element.find(`.${this.options.linkClass}.${this.options.linkActiveClass}`);
  288. if ($activeTab.length) {
  289. this._collapseTab($activeTab);
  290. /**
  291. * Fires when the plugin has successfully collapsed tabs.
  292. * @event Tabs#collapse
  293. */
  294. this.$element.trigger('collapse.zf.tabs', [$activeTab]);
  295. }
  296. }
  297. /**
  298. * Public method for selecting a content pane to display.
  299. * @param {jQuery | String} elem - jQuery object or string of the id of the pane to display.
  300. * @param {boolean} historyHandled - browser has already handled a history update
  301. * @function
  302. */
  303. selectTab(elem, historyHandled) {
  304. var idStr;
  305. if (typeof elem === 'object') {
  306. idStr = elem[0].id;
  307. } else {
  308. idStr = elem;
  309. }
  310. if (idStr.indexOf('#') < 0) {
  311. idStr = `#${idStr}`;
  312. }
  313. var $target = this.$tabTitles.has(`[href$="${idStr}"]`);
  314. this._handleTabChange($target, historyHandled);
  315. };
  316. /**
  317. * Sets the height of each panel to the height of the tallest panel.
  318. * If enabled in options, gets called on media query change.
  319. * If loading content via external source, can be called directly or with _reflow.
  320. * If enabled with `data-match-height="true"`, tabs sets to equal height
  321. * @function
  322. * @private
  323. */
  324. _setHeight() {
  325. var max = 0,
  326. _this = this; // Lock down the `this` value for the root tabs object
  327. this.$tabContent
  328. .find(`.${this.options.panelClass}`)
  329. .css('height', '')
  330. .each(function() {
  331. var panel = $(this),
  332. isActive = panel.hasClass(`${_this.options.panelActiveClass}`); // get the options from the parent instead of trying to get them from the child
  333. if (!isActive) {
  334. panel.css({'visibility': 'hidden', 'display': 'block'});
  335. }
  336. var temp = this.getBoundingClientRect().height;
  337. if (!isActive) {
  338. panel.css({
  339. 'visibility': '',
  340. 'display': ''
  341. });
  342. }
  343. max = temp > max ? temp : max;
  344. })
  345. .css('height', `${max}px`);
  346. }
  347. /**
  348. * Destroys an instance of tabs.
  349. * @fires Tabs#destroyed
  350. */
  351. _destroy() {
  352. this.$element
  353. .find(`.${this.options.linkClass}`)
  354. .off('.zf.tabs').hide().end()
  355. .find(`.${this.options.panelClass}`)
  356. .hide();
  357. if (this.options.matchHeight) {
  358. if (this._setHeightMqHandler != null) {
  359. $(window).off('changed.zf.mediaquery', this._setHeightMqHandler);
  360. }
  361. }
  362. if (this.options.deepLink) {
  363. $(window).off('hashchange', this._checkDeepLink);
  364. }
  365. if (this.onLoadListener) {
  366. $(window).off(this.onLoadListener);
  367. }
  368. }
  369. }
  370. Tabs.defaults = {
  371. /**
  372. * Link the location hash to the active pane.
  373. * Set the location hash when the active pane changes, and open the corresponding pane when the location changes.
  374. * @option
  375. * @type {boolean}
  376. * @default false
  377. */
  378. deepLink: false,
  379. /**
  380. * If `deepLink` is enabled, adjust the deep link scroll to make sure the top of the tab panel is visible
  381. * @option
  382. * @type {boolean}
  383. * @default false
  384. */
  385. deepLinkSmudge: false,
  386. /**
  387. * If `deepLinkSmudge` is enabled, animation time (ms) for the deep link adjustment
  388. * @option
  389. * @type {number}
  390. * @default 300
  391. */
  392. deepLinkSmudgeDelay: 300,
  393. /**
  394. * If `deepLink` is enabled, update the browser history with the open tab
  395. * @option
  396. * @type {boolean}
  397. * @default false
  398. */
  399. updateHistory: false,
  400. /**
  401. * Allows the window to scroll to content of active pane on load.
  402. * Not recommended if more than one tab panel per page.
  403. * @option
  404. * @type {boolean}
  405. * @default false
  406. */
  407. autoFocus: false,
  408. /**
  409. * Allows keyboard input to 'wrap' around the tab links.
  410. * @option
  411. * @type {boolean}
  412. * @default true
  413. */
  414. wrapOnKeys: true,
  415. /**
  416. * Allows the tab content panes to match heights if set to true.
  417. * @option
  418. * @type {boolean}
  419. * @default false
  420. */
  421. matchHeight: false,
  422. /**
  423. * Allows active tabs to collapse when clicked.
  424. * @option
  425. * @type {boolean}
  426. * @default false
  427. */
  428. activeCollapse: false,
  429. /**
  430. * Class applied to `li`'s in tab link list.
  431. * @option
  432. * @type {string}
  433. * @default 'tabs-title'
  434. */
  435. linkClass: 'tabs-title',
  436. /**
  437. * Class applied to the active `li` in tab link list.
  438. * @option
  439. * @type {string}
  440. * @default 'is-active'
  441. */
  442. linkActiveClass: 'is-active',
  443. /**
  444. * Class applied to the content containers.
  445. * @option
  446. * @type {string}
  447. * @default 'tabs-panel'
  448. */
  449. panelClass: 'tabs-panel',
  450. /**
  451. * Class applied to the active content container.
  452. * @option
  453. * @type {string}
  454. * @default 'is-active'
  455. */
  456. panelActiveClass: 'is-active'
  457. };
  458. export {Tabs};