jquery.slicknav.js 16 KB

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