jquery.navgoco.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. * jQuery Navgoco Menus Plugin v0.1.5 (2013-09-07)
  3. * https://github.com/tefra/navgoco
  4. *
  5. * Copyright (c) 2013 Chris T (@tefra)
  6. * BSD - https://github.com/tefra/navgoco/blob/master/LICENSE-BSD
  7. */
  8. (function($) {
  9. "use strict";
  10. /**
  11. * Plugin Constructor. Every menu must have a unique id which will either
  12. * be the actual id attribute or its index in the page.
  13. *
  14. * @param {Element} el
  15. * @param {Object} options
  16. * @param {Integer} idx
  17. * @returns {Object} Plugin Instance
  18. */
  19. var Plugin = function(el, options, idx) {
  20. this.el = el;
  21. this.$el = $(el);
  22. this.options = options;
  23. this.uuid = this.$el.attr('id') ? this.$el.attr('id') : idx;
  24. this.state = {};
  25. this.init();
  26. return this;
  27. };
  28. /**
  29. * Plugin methods
  30. */
  31. Plugin.prototype = {
  32. /**
  33. * Load cookie, assign a unique data-index attribute to
  34. * all sub-menus and show|hide them according to cookie
  35. * or based on the parent open class. Find all parent li > a
  36. * links add the carent if it's on and attach the event click
  37. * to them.
  38. */
  39. init: function() {
  40. var self = this;
  41. self._load();
  42. self.$el.find('ul').each(function(idx) {
  43. var sub = $(this);
  44. sub.attr('data-index', idx);
  45. if (self.options.save && self.state.hasOwnProperty(idx)) {
  46. sub.parent().addClass(self.options.openClass);
  47. sub.show();
  48. } else if (sub.parent().hasClass(self.options.openClass)) {
  49. sub.show();
  50. self.state[idx] = 1;
  51. } else {
  52. sub.hide();
  53. }
  54. });
  55. if (self.options.caret) {
  56. self.$el.find("li:has(ul) > a").append(self.options.caret);
  57. }
  58. var links = self.$el.find("li > a");
  59. links.on('click', function(event) {
  60. event.stopPropagation();
  61. var sub = $(this).next();
  62. sub = sub.length > 0 ? sub : false;
  63. self.options.onClickBefore.call(this, event, sub);
  64. if (sub) {
  65. event.preventDefault();
  66. self._toggle(sub, sub.is(":hidden"));
  67. self._save();
  68. } else {
  69. if (self.options.accordion) {
  70. var allowed = self.state = self._parents($(this));
  71. self.$el.find('ul').filter(':visible').each(function() {
  72. var sub = $(this),
  73. idx = sub.attr('data-index');
  74. if (!allowed.hasOwnProperty(idx)) {
  75. self._toggle(sub, false);
  76. }
  77. });
  78. self._save();
  79. }
  80. }
  81. self.options.onClickAfter.call(this, event, sub);
  82. });
  83. },
  84. /**
  85. * Accepts a JQuery Element and a boolean flag. If flag is false it removes the `open` css
  86. * class from the parent li and slides up the sub-menu. If flag is open it adds the `open`
  87. * css class to the parent li and slides down the menu. If accordion mode is on all
  88. * sub-menus except the direct parent tree will close. Internally an object with the menus
  89. * states is maintained for later save duty.
  90. *
  91. * @param {Element} sub
  92. * @param {Boolean} open
  93. */
  94. _toggle: function(sub, open) {
  95. var self = this,
  96. idx = sub.attr('data-index'),
  97. parent = sub.parent();
  98. self.options.onToggleBefore.call(this, sub, open);
  99. if (open) {
  100. parent.addClass(self.options.openClass);
  101. sub.slideDown(self.options.slide);
  102. self.state[idx] = 1;
  103. if (self.options.accordion) {
  104. var allowed = self.state = self._parents(sub);
  105. allowed[idx] = self.state[idx] = 1;
  106. self.$el.find('ul').filter(':visible').each(function() {
  107. var sub = $(this),
  108. idx = sub.attr('data-index');
  109. if (!allowed.hasOwnProperty(idx)) {
  110. self._toggle(sub, false);
  111. }
  112. });
  113. }
  114. } else {
  115. parent.removeClass(self.options.openClass);
  116. sub.slideUp(self.options.slide);
  117. self.state[idx] = 0;
  118. }
  119. self.options.onToggleAfter.call(this, sub, open);
  120. },
  121. /**
  122. * Returns all parents of a sub-menu. When obj is true It returns an object with indexes for
  123. * keys and the elements as values, if obj is false the object is filled with the value `1`.
  124. *
  125. * @since v0.1.2
  126. * @param {Element} sub
  127. * @param {Boolean} obj
  128. * @returns {Object}
  129. */
  130. _parents: function(sub, obj) {
  131. var result = {},
  132. parent = sub.parent(),
  133. parents = parent.parents('ul');
  134. parents.each(function() {
  135. var par = $(this),
  136. idx = par.attr('data-index');
  137. if (!idx) {
  138. return false;
  139. }
  140. result[idx] = obj ? par : 1;
  141. });
  142. return result;
  143. },
  144. /**
  145. * If `save` option is on the internal object that keeps track of the sub-menus states is
  146. * saved with a cookie. For size reasons only the open sub-menus indexes are stored. *
  147. */
  148. _save: function() {
  149. if (this.options.save) {
  150. var save = {};
  151. for (var key in this.state) {
  152. if (this.state[key] === 1) {
  153. save[key] = 1;
  154. }
  155. }
  156. cookie[this.uuid] = this.state = save;
  157. $.cookie(this.options.cookie.name, JSON.stringify(cookie), this.options.cookie);
  158. }
  159. },
  160. /**
  161. * If `save` option is on it reads the cookie data. The cookie contains data for all
  162. * navgoco menus so the read happens only once and stored in the global `cookie` var.
  163. */
  164. _load: function() {
  165. if (this.options.save) {
  166. if (cookie === null) {
  167. var data = $.cookie(this.options.cookie.name);
  168. cookie = (data) ? JSON.parse(data) : {};
  169. }
  170. this.state = cookie.hasOwnProperty(this.uuid) ? cookie[this.uuid] : {};
  171. }
  172. },
  173. /**
  174. * Public method toggle to manually show|hide sub-menus. If no indexes are provided all
  175. * items will be toggled. You can pass sub-menus indexes as regular params. eg:
  176. * navgoco('toggle', true, 1, 2, 3, 4, 5);
  177. *
  178. * Since v0.1.2 it will also open parents when providing sub-menu indexes.
  179. *
  180. * @param {Boolean} open
  181. */
  182. toggle: function(open) {
  183. var self = this,
  184. length = arguments.length;
  185. if (length <= 1) {
  186. self.$el.find('ul').each(function() {
  187. var sub = $(this);
  188. self._toggle(sub, open);
  189. });
  190. } else {
  191. var idx,
  192. list = {},
  193. args = Array.prototype.slice.call(arguments, 1);
  194. length--;
  195. for (var i = 0; i < length; i++) {
  196. idx = args[i];
  197. var sub = self.$el.find('ul[data-index="' + idx + '"]').first();
  198. if (sub) {
  199. list[idx] = sub;
  200. if (open) {
  201. var parents = self._parents(sub, true);
  202. for (var pIdx in parents) {
  203. if (!list.hasOwnProperty(pIdx)) {
  204. list[pIdx] = parents[pIdx];
  205. }
  206. }
  207. }
  208. }
  209. }
  210. for (idx in list) {
  211. self._toggle(list[idx], open);
  212. }
  213. }
  214. self._save();
  215. },
  216. /**
  217. * Removes instance from JQuery data cache and unbinds events.
  218. */
  219. destroy: function() {
  220. $.removeData(this.$el);
  221. this.$el.find("li:has(ul) > a").unbind('click');
  222. }
  223. };
  224. /**
  225. * A JQuery plugin wrapper for navgoco. It prevents from multiple instances and also handles
  226. * public methods calls. If we attempt to call a public method on an element that doesn't have
  227. * a navgoco instance, one will be created for it with the default options.
  228. *
  229. * @param {Object|String} options
  230. */
  231. $.fn.navgoco = function(options) {
  232. if (typeof options === 'string' && options.charAt(0) !== '_' && options !== 'init') {
  233. var callback = true,
  234. args = Array.prototype.slice.call(arguments, 1);
  235. } else {
  236. options = $.extend({}, $.fn.navgoco.defaults, options || {});
  237. if (!$.cookie) {
  238. options.save = false;
  239. }
  240. }
  241. return this.each(function(idx) {
  242. var $this = $(this),
  243. obj = $this.data('navgoco');
  244. if (!obj) {
  245. obj = new Plugin(this, callback ? $.fn.navgoco.defaults : options, idx);
  246. $this.data('navgoco', obj);
  247. }
  248. if (callback) {
  249. obj[options].apply(obj, args);
  250. }
  251. });
  252. };
  253. /**
  254. * Global var holding all navgoco menus open states
  255. *
  256. * @type {Object}
  257. */
  258. var cookie = null;
  259. /**
  260. * Default navgoco options
  261. *
  262. * @type {Object}
  263. */
  264. $.fn.navgoco.defaults = {
  265. caret: '<span class="caret"></span>',
  266. accordion: false,
  267. openClass: 'open',
  268. save: true,
  269. cookie: {
  270. name: 'navgoco',
  271. expires: false,
  272. path: '/'
  273. },
  274. slide: {
  275. duration: 400,
  276. easing: 'swing'
  277. },
  278. onClickBefore: $.noop,
  279. onClickAfter: $.noop,
  280. onToggleBefore: $.noop,
  281. onToggleAfter: $.noop
  282. };
  283. })(jQuery);