jquery.slicknav.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. ;(function ($, document, window) {
  2. var
  3. // default settings object.
  4. defaults = {
  5. label: 'MENU',
  6. duplicate: true,
  7. duration: 200,
  8. easingOpen: 'swing',
  9. easingClose: 'swing',
  10. closedSymbol: '►',
  11. openedSymbol: '▼',
  12. prependTo: 'body',
  13. appendTo: '',
  14. parentTag: 'a',
  15. closeOnClick: false,
  16. allowParentLinks: false,
  17. nestedParentLinks: true,
  18. showChildren: false,
  19. removeIds: true,
  20. removeClasses: false,
  21. removeStyles: false,
  22. brand: '',
  23. animations: 'jquery',
  24. init: function () {},
  25. beforeOpen: function () {},
  26. beforeClose: function () {},
  27. afterOpen: function () {},
  28. afterClose: function () {}
  29. },
  30. mobileMenu = 'slicknav',
  31. prefix = 'slicknav',
  32. Keyboard = {
  33. DOWN: 40,
  34. ENTER: 13,
  35. ESCAPE: 27,
  36. LEFT: 37,
  37. RIGHT: 39,
  38. SPACE: 32,
  39. TAB: 9,
  40. UP: 38,
  41. };
  42. function Plugin(element, options) {
  43. this.element = element;
  44. // jQuery has an extend method which merges the contents of two or
  45. // more objects, storing the result in the first object. The first object
  46. // is generally empty as we don't want to alter the default options for
  47. // future instances of the plugin
  48. this.settings = $.extend({}, defaults, options);
  49. // Don't remove IDs by default if duplicate is false
  50. if (!this.settings.duplicate && !options.hasOwnProperty("removeIds")) {
  51. this.settings.removeIds = false;
  52. }
  53. this._defaults = defaults;
  54. this._name = mobileMenu;
  55. this.init();
  56. }
  57. Plugin.prototype.init = function () {
  58. var $this = this,
  59. menu = $(this.element),
  60. settings = this.settings,
  61. iconClass,
  62. menuBar;
  63. // clone menu if needed
  64. if (settings.duplicate) {
  65. $this.mobileNav = menu.clone();
  66. } else {
  67. $this.mobileNav = menu;
  68. }
  69. // remove IDs if set
  70. if (settings.removeIds) {
  71. $this.mobileNav.removeAttr('id');
  72. $this.mobileNav.find('*').each(function (i, e) {
  73. $(e).removeAttr('id');
  74. });
  75. }
  76. // remove classes if set
  77. if (settings.removeClasses) {
  78. $this.mobileNav.removeAttr('class');
  79. $this.mobileNav.find('*').each(function (i, e) {
  80. $(e).removeAttr('class');
  81. });
  82. }
  83. // remove styles if set
  84. if (settings.removeStyles) {
  85. $this.mobileNav.removeAttr('style');
  86. $this.mobileNav.find('*').each(function (i, e) {
  87. $(e).removeAttr('style');
  88. });
  89. }
  90. // styling class for the button
  91. iconClass = prefix + '_icon';
  92. if (settings.label === '') {
  93. iconClass += ' ' + prefix + '_no-text';
  94. }
  95. if (settings.parentTag == 'a') {
  96. settings.parentTag = 'a href="#"';
  97. }
  98. // create menu bar
  99. $this.mobileNav.attr('class', prefix + '_nav');
  100. menuBar = $('<div class="' + prefix + '_menu"></div>');
  101. if (settings.brand !== '') {
  102. var brand = $('<div class="' + prefix + '_brand">'+settings.brand+'</div>');
  103. $(menuBar).append(brand);
  104. }
  105. $this.btn = $(
  106. ['<' + settings.parentTag + ' aria-haspopup="true" role="button" tabindex="0" class="' + prefix + '_btn ' + prefix + '_collapsed">',
  107. '<span class="' + prefix + '_menutxt">' + settings.label + '</span>',
  108. '<span class="' + iconClass + '">',
  109. '<span class="' + prefix + '_icon-bar"></span>',
  110. '<span class="' + prefix + '_icon-bar"></span>',
  111. '<span class="' + prefix + '_icon-bar"></span>',
  112. '</span>',
  113. '</' + settings.parentTag + '>'
  114. ].join('')
  115. );
  116. $(menuBar).append($this.btn);
  117. if(settings.appendTo !== '') {
  118. $(settings.appendTo).append(menuBar);
  119. } else {
  120. $(settings.prependTo).prepend(menuBar);
  121. }
  122. menuBar.append($this.mobileNav);
  123. // iterate over structure adding additional structure
  124. var items = $this.mobileNav.find('li');
  125. $(items).each(function () {
  126. var item = $(this),
  127. data = {};
  128. data.children = item.children('ul').attr('role', 'menu');
  129. item.data('menu', data);
  130. // if a list item has a nested menu
  131. if (data.children.length > 0) {
  132. // select all text before the child menu
  133. // check for anchors
  134. var a = item.contents(),
  135. containsAnchor = false,
  136. nodes = [];
  137. $(a).each(function () {
  138. if (!$(this).is('ul')) {
  139. nodes.push(this);
  140. } else {
  141. return false;
  142. }
  143. if($(this).is("a")) {
  144. containsAnchor = true;
  145. }
  146. });
  147. var wrapElement = $(
  148. '<' + settings.parentTag + ' role="menuitem" aria-haspopup="true" tabindex="-1" class="' + prefix + '_item"/>'
  149. );
  150. // wrap item text with tag and add classes unless we are separating parent links
  151. if ((!settings.allowParentLinks || settings.nestedParentLinks) || !containsAnchor) {
  152. var $wrap = $(nodes).wrapAll(wrapElement).parent();
  153. $wrap.addClass(prefix+'_row');
  154. } else
  155. $(nodes).wrapAll('<span class="'+prefix+'_parent-link '+prefix+'_row"/>').parent();
  156. if (!settings.showChildren) {
  157. item.addClass(prefix+'_collapsed');
  158. } else {
  159. item.addClass(prefix+'_open');
  160. }
  161. item.addClass(prefix+'_parent');
  162. // create parent arrow. wrap with link if parent links and separating
  163. var arrowElement = $('<span class="'+prefix+'_arrow">'+(settings.showChildren?settings.openedSymbol:settings.closedSymbol)+'</span>');
  164. if (settings.allowParentLinks && !settings.nestedParentLinks && containsAnchor)
  165. arrowElement = arrowElement.wrap(wrapElement).parent();
  166. //append arrow
  167. $(nodes).last().after(arrowElement);
  168. } else if ( item.children().length === 0) {
  169. item.addClass(prefix+'_txtnode');
  170. }
  171. // accessibility for links
  172. item.children('a').attr('role', 'menuitem').click(function(event){
  173. //Ensure that it's not a parent
  174. if (settings.closeOnClick && !$(event.target).parent().closest('li').hasClass(prefix+'_parent')) {
  175. //Emulate menu close if set
  176. $($this.btn).click();
  177. }
  178. });
  179. //also close on click if parent links are set
  180. if (settings.closeOnClick && settings.allowParentLinks) {
  181. item.children('a').children('a').click(function (event) {
  182. //Emulate menu close
  183. $($this.btn).click();
  184. });
  185. item.find('.'+prefix+'_parent-link a:not(.'+prefix+'_item)').click(function(event){
  186. //Emulate menu close
  187. $($this.btn).click();
  188. });
  189. }
  190. });
  191. // structure is in place, now hide appropriate items
  192. $(items).each(function () {
  193. var data = $(this).data('menu');
  194. if (!settings.showChildren){
  195. $this._visibilityToggle(data.children, null, false, null, true);
  196. }
  197. });
  198. // finally toggle entire menu
  199. $this._visibilityToggle($this.mobileNav, null, false, 'init', true);
  200. // accessibility for menu button
  201. $this.mobileNav.attr('role','menu');
  202. // outline prevention when using mouse
  203. $(document).mousedown(function(){
  204. $this._outlines(false);
  205. });
  206. $(document).keyup(function(){
  207. $this._outlines(true);
  208. });
  209. // menu button click
  210. $($this.btn).click(function (e) {
  211. e.preventDefault();
  212. $this._menuToggle();
  213. });
  214. // click on menu parent
  215. $this.mobileNav.on('click', '.' + prefix + '_item', function (e) {
  216. e.preventDefault();
  217. $this._itemClick($(this));
  218. });
  219. // check for keyboard events on menu button and menu parents
  220. $($this.btn).keydown(function (e) {
  221. var ev = e || event;
  222. switch(ev.keyCode) {
  223. case Keyboard.ENTER:
  224. case Keyboard.SPACE:
  225. case Keyboard.DOWN:
  226. e.preventDefault();
  227. if (ev.keyCode !== Keyboard.DOWN || !$($this.btn).hasClass(prefix+'_open')){
  228. $this._menuToggle();
  229. }
  230. $($this.btn).next().find('[role="menuitem"]').first().focus();
  231. break;
  232. }
  233. });
  234. $this.mobileNav.on('keydown', '.'+prefix+'_item', function(e) {
  235. var ev = e || event;
  236. switch(ev.keyCode) {
  237. case Keyboard.ENTER:
  238. e.preventDefault();
  239. $this._itemClick($(e.target));
  240. break;
  241. case Keyboard.RIGHT:
  242. e.preventDefault();
  243. if ($(e.target).parent().hasClass(prefix+'_collapsed')) {
  244. $this._itemClick($(e.target));
  245. }
  246. $(e.target).next().find('[role="menuitem"]').first().focus();
  247. break;
  248. }
  249. });
  250. $this.mobileNav.on('keydown', '[role="menuitem"]', function(e) {
  251. var ev = e || event;
  252. switch(ev.keyCode){
  253. case Keyboard.DOWN:
  254. e.preventDefault();
  255. var allItems = $(e.target).parent().parent().children().children('[role="menuitem"]:visible');
  256. var idx = allItems.index( e.target );
  257. var nextIdx = idx + 1;
  258. if (allItems.length <= nextIdx) {
  259. nextIdx = 0;
  260. }
  261. var next = allItems.eq( nextIdx );
  262. next.focus();
  263. break;
  264. case Keyboard.UP:
  265. e.preventDefault();
  266. var allItems = $(e.target).parent().parent().children().children('[role="menuitem"]:visible');
  267. var idx = allItems.index( e.target );
  268. var next = allItems.eq( idx - 1 );
  269. next.focus();
  270. break;
  271. case Keyboard.LEFT:
  272. e.preventDefault();
  273. if ($(e.target).parent().parent().parent().hasClass(prefix+'_open')) {
  274. var parent = $(e.target).parent().parent().prev();
  275. parent.focus();
  276. $this._itemClick(parent);
  277. } else if ($(e.target).parent().parent().hasClass(prefix+'_nav')){
  278. $this._menuToggle();
  279. $($this.btn).focus();
  280. }
  281. break;
  282. case Keyboard.ESCAPE:
  283. e.preventDefault();
  284. $this._menuToggle();
  285. $($this.btn).focus();
  286. break;
  287. }
  288. });
  289. // allow links clickable within parent tags if set
  290. if (settings.allowParentLinks && settings.nestedParentLinks) {
  291. $('.'+prefix+'_item a').click(function(e){
  292. e.stopImmediatePropagation();
  293. });
  294. }
  295. };
  296. //toggle menu
  297. Plugin.prototype._menuToggle = function (el) {
  298. var $this = this;
  299. var btn = $this.btn;
  300. var mobileNav = $this.mobileNav;
  301. if (btn.hasClass(prefix+'_collapsed')) {
  302. btn.removeClass(prefix+'_collapsed');
  303. btn.addClass(prefix+'_open');
  304. } else {
  305. btn.removeClass(prefix+'_open');
  306. btn.addClass(prefix+'_collapsed');
  307. }
  308. btn.addClass(prefix+'_animating');
  309. $this._visibilityToggle(mobileNav, btn.parent(), true, btn);
  310. };
  311. // toggle clicked items
  312. Plugin.prototype._itemClick = function (el) {
  313. var $this = this;
  314. var settings = $this.settings;
  315. var data = el.data('menu');
  316. if (!data) {
  317. data = {};
  318. data.arrow = el.children('.'+prefix+'_arrow');
  319. data.ul = el.next('ul');
  320. data.parent = el.parent();
  321. //Separated parent link structure
  322. if (data.parent.hasClass(prefix+'_parent-link')) {
  323. data.parent = el.parent().parent();
  324. data.ul = el.parent().next('ul');
  325. }
  326. el.data('menu', data);
  327. }
  328. if (data.parent.hasClass(prefix+'_collapsed')) {
  329. data.arrow.html(settings.openedSymbol);
  330. data.parent.removeClass(prefix+'_collapsed');
  331. data.parent.addClass(prefix+'_open');
  332. data.parent.addClass(prefix+'_animating');
  333. $this._visibilityToggle(data.ul, data.parent, true, el);
  334. } else {
  335. data.arrow.html(settings.closedSymbol);
  336. data.parent.addClass(prefix+'_collapsed');
  337. data.parent.removeClass(prefix+'_open');
  338. data.parent.addClass(prefix+'_animating');
  339. $this._visibilityToggle(data.ul, data.parent, true, el);
  340. }
  341. };
  342. // toggle actual visibility and accessibility tags
  343. Plugin.prototype._visibilityToggle = function(el, parent, animate, trigger, init) {
  344. var $this = this;
  345. var settings = $this.settings;
  346. var items = $this._getActionItems(el);
  347. var duration = 0;
  348. if (animate) {
  349. duration = settings.duration;
  350. }
  351. function afterOpen(trigger, parent) {
  352. $(trigger).removeClass(prefix+'_animating');
  353. $(parent).removeClass(prefix+'_animating');
  354. //Fire afterOpen callback
  355. if (!init) {
  356. settings.afterOpen(trigger);
  357. }
  358. }
  359. function afterClose(trigger, parent) {
  360. el.attr('aria-hidden','true');
  361. items.attr('tabindex', '-1');
  362. $this._setVisAttr(el, true);
  363. el.hide(); //jQuery 1.7 bug fix
  364. $(trigger).removeClass(prefix+'_animating');
  365. $(parent).removeClass(prefix+'_animating');
  366. //Fire init or afterClose callback
  367. if (!init){
  368. settings.afterClose(trigger);
  369. } else if (trigger == 'init'){
  370. settings.init();
  371. }
  372. }
  373. if (el.hasClass(prefix+'_hidden')) {
  374. el.removeClass(prefix+'_hidden');
  375. //Fire beforeOpen callback
  376. if (!init) {
  377. settings.beforeOpen(trigger);
  378. }
  379. if (settings.animations === 'jquery') {
  380. el.stop(true,true).slideDown(duration, settings.easingOpen, function(){
  381. afterOpen(trigger, parent);
  382. });
  383. } else if(settings.animations === 'velocity') {
  384. el.velocity("finish").velocity("slideDown", {
  385. duration: duration,
  386. easing: settings.easingOpen,
  387. complete: function() {
  388. afterOpen(trigger, parent);
  389. }
  390. });
  391. }
  392. el.attr('aria-hidden','false');
  393. items.attr('tabindex', '0');
  394. $this._setVisAttr(el, false);
  395. } else {
  396. el.addClass(prefix+'_hidden');
  397. //Fire init or beforeClose callback
  398. if (!init){
  399. settings.beforeClose(trigger);
  400. }
  401. if (settings.animations === 'jquery') {
  402. el.stop(true,true).slideUp(duration, this.settings.easingClose, function() {
  403. afterClose(trigger, parent)
  404. });
  405. } else if (settings.animations === 'velocity') {
  406. el.velocity("finish").velocity("slideUp", {
  407. duration: duration,
  408. easing: settings.easingClose,
  409. complete: function() {
  410. afterClose(trigger, parent);
  411. }
  412. });
  413. }
  414. }
  415. };
  416. // set attributes of element and children based on visibility
  417. Plugin.prototype._setVisAttr = function(el, hidden) {
  418. var $this = this;
  419. // select all parents that aren't hidden
  420. var nonHidden = el.children('li').children('ul').not('.'+prefix+'_hidden');
  421. // iterate over all items setting appropriate tags
  422. if (!hidden) {
  423. nonHidden.each(function(){
  424. var ul = $(this);
  425. ul.attr('aria-hidden','false');
  426. var items = $this._getActionItems(ul);
  427. items.attr('tabindex', '0');
  428. $this._setVisAttr(ul, hidden);
  429. });
  430. } else {
  431. nonHidden.each(function(){
  432. var ul = $(this);
  433. ul.attr('aria-hidden','true');
  434. var items = $this._getActionItems(ul);
  435. items.attr('tabindex', '-1');
  436. $this._setVisAttr(ul, hidden);
  437. });
  438. }
  439. };
  440. // get all 1st level items that are clickable
  441. Plugin.prototype._getActionItems = function(el) {
  442. var data = el.data("menu");
  443. if (!data) {
  444. data = {};
  445. var items = el.children('li');
  446. var anchors = items.find('a');
  447. data.links = anchors.add(items.find('.'+prefix+'_item'));
  448. el.data('menu', data);
  449. }
  450. return data.links;
  451. };
  452. Plugin.prototype._outlines = function(state) {
  453. if (!state) {
  454. $('.'+prefix+'_item, .'+prefix+'_btn').css('outline','none');
  455. } else {
  456. $('.'+prefix+'_item, .'+prefix+'_btn').css('outline','');
  457. }
  458. };
  459. Plugin.prototype.toggle = function(){
  460. var $this = this;
  461. $this._menuToggle();
  462. };
  463. Plugin.prototype.open = function(){
  464. var $this = this;
  465. if ($this.btn.hasClass(prefix+'_collapsed')) {
  466. $this._menuToggle();
  467. }
  468. };
  469. Plugin.prototype.close = function(){
  470. var $this = this;
  471. if ($this.btn.hasClass(prefix+'_open')) {
  472. $this._menuToggle();
  473. }
  474. };
  475. $.fn[mobileMenu] = function ( options ) {
  476. var args = arguments;
  477. // Is the first parameter an object (options), or was omitted, instantiate a new instance
  478. if (options === undefined || typeof options === 'object') {
  479. return this.each(function () {
  480. // Only allow the plugin to be instantiated once due to methods
  481. if (!$.data(this, 'plugin_' + mobileMenu)) {
  482. // if it has no instance, create a new one, pass options to our plugin constructor,
  483. // and store the plugin instance in the elements jQuery data object.
  484. $.data(this, 'plugin_' + mobileMenu, new Plugin( this, options ));
  485. }
  486. });
  487. // If is a string and doesn't start with an underscore or 'init' function, treat this as a call to a public method.
  488. } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
  489. // Cache the method call to make it possible to return a value
  490. var returns;
  491. this.each(function () {
  492. var instance = $.data(this, 'plugin_' + mobileMenu);
  493. // Tests that there's already a plugin-instance and checks that the requested public method exists
  494. if (instance instanceof Plugin && typeof instance[options] === 'function') {
  495. // Call the method of our plugin instance, and pass it the supplied arguments.
  496. returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
  497. }
  498. });
  499. // If the earlier cached method gives a value back return the value, otherwise return this to preserve chainability.
  500. return returns !== undefined ? returns : this;
  501. }
  502. };
  503. }(jQuery, document, window));