/
priority-nav.js
624 lines (526 loc) · 18.1 KB
/
priority-nav.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
/*
* priority-nav - v1.0.4 | (c) 2015 @gijsroge | MIT license
* Repository: https://github.com/gijsroge/priority-navigation.git
* Description: Priority+ pattern navigation that hides menu items if they don't fit on screen.
* Demo: http://gijsroge.github.io/priority-nav.js/
*/
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define("priorityNav", factory(root));
} else if (typeof exports === "object") {
module.exports = factory(root);
} else {
root.priorityNav = factory(root);
}
})(window || this, function (root) {
"use strict";
/**
* Variables
*/
var priorityNav = {}; // Object for public APIs
var breaks = []; // Object to store instances with breakpoints where the instances menu item"s didin"t fit.
var supports = !!document.querySelector && !!root.addEventListener; // Feature test
var settings = {};
var instance = 0;
var count = 0;
var mainNavWrapper, totalWidth, restWidth, mainNav, navDropdown, navDropdownToggle, dropDownWidth, toggleWrapper;
/**
* Default settings
* @type {{initClass: string, navDropdown: string, navDropdownToggle: string, mainNavWrapper: string, moved: Function, movedBack: Function}}
*/
var defaults = {
initClass: "js-priorityNav",
mainNavWrapper: "nav",
mainNav: "ul",
navDropdown: ".nav__dropdown",
navDropdownToggle: ".nav__dropdown-toggle",
navDropdownLabel: "more",
throttleDelay: 50,
offsetPixels: 0,
count: true,
//Callbacks
moved: function () {
},
movedBack: function () {
}
};
/**
* A simple forEach() implementation for Arrays, Objects and NodeLists
* @private
* @param {Array|Object|NodeList} collection Collection of items to iterate
* @param {Function} callback Callback function for each iteration
* @param {Array|Object|NodeList} scope Object/NodeList/Array that forEach is iterating over (aka `this`)
*/
var forEach = function (collection, callback, scope) {
if (Object.prototype.toString.call(collection) === "[object Object]") {
for (var prop in collection) {
if (Object.prototype.hasOwnProperty.call(collection, prop)) {
callback.call(scope, collection[prop], prop, collection);
}
}
} else {
for (var i = 0, len = collection.length; i < len; i++) {
callback.call(scope, collection[i], i, collection);
}
}
};
/**
* Get the closest matching element up the DOM tree
* @param {Element} elem Starting element
* @param {String} selector Selector to match against (class, ID, or data attribute)
* @return {Boolean|Element} Returns false if not match found
*/
var getClosest = function (elem, selector) {
var firstChar = selector.charAt(0);
for (; elem && elem !== document; elem = elem.parentNode) {
if (firstChar === ".") {
if (elem.classList.contains(selector.substr(1))) {
return elem;
}
} else if (firstChar === "#") {
if (elem.id === selector.substr(1)) {
return elem;
}
} else if (firstChar === "[") {
if (elem.hasAttribute(selector.substr(1, selector.length - 2))) {
return elem;
}
}
}
return false;
};
/**
* Merge defaults with user options
* @private
* @param {Object} defaults Default settings
* @param {Object} options User options
* @returns {Object} Merged values of defaults and options
*/
var extend = function (defaults, options) {
var extended = {};
forEach(defaults, function (value, prop) {
extended[prop] = defaults[prop];
});
forEach(options, function (value, prop) {
extended[prop] = options[prop];
});
return extended;
};
/**
* Debounced resize to throttle execution
* @param func
* @param wait
* @param immediate
* @returns {Function}
*/
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
/**
* Toggle class on element
* @param el
* @param className
*/
var toggleClass = function (el, className) {
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(" ");
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0)
classes.splice(existingIndex, 1); else
classes.push(className);
el.className = classes.join(" ");
}
};
/**
* Check if dropdown menu is already on page before creating it
* @param mainNavWrapper
*/
var prepareHtml = function (_this) {
/**
* Create dropdow menu
* @type {HTMLElement}
*/
toggleWrapper = document.createElement("span");
navDropdown = document.createElement("ul");
navDropdownToggle = document.createElement("button");
/**
* Set label for dropdown toggle
* @type {string}
*/
navDropdownToggle.innerHTML = settings.navDropdownLabel;
/**
* Move elements to the right spot
*/
_this.insertAfter(toggleWrapper, _this.querySelector(mainNav));
toggleWrapper.appendChild(navDropdown);
toggleWrapper.appendChild(navDropdownToggle);
/**
* Add classes so we can target elements
*/
navDropdown.classList.add(settings.navDropdown.substr(1));
navDropdown.classList.add("priority-nav__dropdown");
navDropdownToggle.classList.add(settings.navDropdownToggle.substr(1));
navDropdownToggle.classList.add("priority-nav__dropdown-toggle");
toggleWrapper.classList.add(settings.navDropdown.substr(1)+"-wrapper");
toggleWrapper.classList.add("priority-nav__wrapper");
_this.classList.add("priority-nav");
};
/**
* Get innerwidth without padding
* @param element
* @returns {number}
*/
var getElementContentWidth = function(element) {
var styles = window.getComputedStyle(element);
var padding = parseFloat(styles.paddingLeft) +
parseFloat(styles.paddingRight);
return element.clientWidth - padding;
};
/**
* Get width
* @param elem
* @returns {number}
*/
var calculateWidths = function (_this) {
totalWidth = getElementContentWidth(_this);
//Check if parent is the navwrapper before calculating its width
if (_this.querySelector(navDropdown).parentNode === _this) {
dropDownWidth = _this.querySelector(navDropdown).offsetWidth;
} else {
dropDownWidth = 0;
}
restWidth = getChildrenWidth(_this) + settings.offsetPixels;
};
/**
* Move item to array
* @param item
*/
priorityNav.doesItFit = function (_this) {
/**
* Check if it is the first run
*/
var delay = _this.getAttribute("instance") === 0 ? delay : settings.throttleDelay;
/**
* Increase instance
*/
instance++;
/**
* Debounced execution of the main logic
*/
(debounce(function () {
/**
* Get the current element"s instance
* @type {string}
*/
var identifier = _this.getAttribute("instance");
/**
* Update width
*/
calculateWidths(_this);
/**
* Keep executing until all menu items that are overflowing are moved
*/
while (totalWidth < restWidth && _this.querySelector(mainNav).children.length > 0) {
//move item to dropdown
priorityNav.toDropdown(_this, identifier);
//recalculate widths
calculateWidths(_this, identifier);
}
/**
* Keep executing until all menu items that are able to move back are moved
*/
while (totalWidth > breaks[identifier][breaks[identifier].length - 1]) {
//move item to menu
priorityNav.toMenu(_this, identifier);
}
/**
* If there are no items in dropdown hide dropdown
*/
if (breaks[identifier].length < 1) {
_this.querySelector(navDropdown).classList.remove("show");
}
/**
* Check if we need to show toggle menu button
*/
showToggle(_this, identifier);
}, delay ))();
};
/**
* Show/hide toggle button
*/
var showToggle = function (_this, identifier) {
if (breaks[identifier].length < 1) {
_this.querySelector(navDropdownToggle).classList.add("priority-nav-is-hidden");
_this.querySelector(navDropdownToggle).classList.remove("priority-nav-is-visible");
_this.classList.remove("priority-nav-has-dropdown");
} else {
_this.querySelector(navDropdownToggle).classList.add("priority-nav-is-visible");
_this.querySelector(navDropdownToggle).classList.remove("priority-nav-is-hidden");
_this.classList.add("priority-nav-has-dropdown");
}
};
/**
* Update count on dropdown toggle button
*/
var updateCount = function (_this, identifier) {
_this.querySelector(navDropdownToggle).dataset.count = breaks[identifier].length;
};
/**
* Move item to dropdown
*/
priorityNav.toDropdown = function (_this, identifier) {
/**
* move last child of navigation menu to dropdown
*/
if (_this.querySelector(navDropdown).firstChild && _this.querySelector(mainNav).children.length > 0) {
_this.querySelector(navDropdown).insertBefore(_this.querySelector(mainNav).lastElementChild, _this.querySelector(navDropdown).firstChild);
} else if (_this.querySelector(mainNav).children.length > 0) {
_this.querySelector(navDropdown).appendChild(_this.querySelector(mainNav).lastElementChild);
}
/**
* store breakpoints
*/
breaks[identifier].push(restWidth);
/**
* check if we need to show toggle menu button
*/
showToggle(_this, identifier);
/**
* update count on dropdown toggle button
*/
if (_this.querySelector(mainNav).children.length > 0 && settings.count) {
updateCount(_this, identifier);
}
/**
* If item has been moved to dropdown trigger the callback
*/
settings.moved();
};
/**
* Move item to menu
*/
priorityNav.toMenu = function (_this, identifier) {
/**
* move last child of navigation menu to dropdown
*/
if (_this.querySelector(navDropdown).children.length > 0) _this.querySelector(mainNav).appendChild(_this.querySelector(navDropdown).firstElementChild);
/**
* remove last breakpoint
*/
breaks[identifier].pop();
/**
* Check if we need to show toggle menu button
*/
showToggle(_this, identifier);
/**
* update count on dropdown toggle button
*/
if (_this.querySelector(mainNav).children.length > 0 && settings.count) {
updateCount(_this, identifier);
}
/**
* If item has been moved back to the main menu trigger the callback
*/
settings.movedBack();
};
/**
* Count width of children and return the value
* @param e
*/
var getChildrenWidth = function (e) {
var children = e.childNodes;
var sum = 0;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType !== 3) {
if(!isNaN(children[i].offsetWidth)){
sum += children[i].offsetWidth;
}
}
}
return sum;
};
/**
* Bind eventlisteners
*/
var listeners = function (_this) {
// Check if an item needs to move
if(window.attachEvent) {
window.attachEvent("onresize", function() {
if(priorityNav.doesItFit)priorityNav.doesItFit(_this);
});
}
else if(window.addEventListener) {
window.addEventListener("resize", function() {
if(priorityNav.doesItFit)priorityNav.doesItFit(_this);
}, true);
}
// Toggle dropdown
_this.querySelector(navDropdownToggle).addEventListener("click", function () {
toggleClass(_this.querySelector(settings.navDropdown), "show");
toggleClass(this, "is-open");
toggleClass(_this, "is-open");
});
/*
* Remove when clicked outside dropdown
*/
document.addEventListener("click", function (event) {
if (!getClosest(event.target, settings.navDropdown) && event.target !== _this.querySelector(navDropdownToggle)) {
_this.querySelector(navDropdown).classList.remove("show");
_this.querySelector(navDropdownToggle).classList.remove("is-open");
_this.classList.remove("is-open");
}
});
/**
* Remove when escape key is pressed
*/
document.onkeydown = function (evt) {
evt = evt || window.event;
if (evt.keyCode === 27) {
navDropdown.classList.remove("show");
navDropdownToggle.classList.remove("is-open");
mainNavWrapper.classList.remove("is-open");
}
};
};
/**
* Remove function
*/
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
};
/*global HTMLCollection */
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
};
/**
* Destroy the current initialization.
* @public
*/
priorityNav.destroy = function () {
// If plugin isn"t already initialized, stop
if (!settings) return;
// Remove feedback class
document.documentElement.classList.remove(settings.initClass);
// Remove toggle
toggleWrapper.remove();
// Remove settings
settings = null;
delete priorityNav.init;
delete priorityNav.doesItFit;
};
/**
* insertAfter function
* @param n
* @param r
*/
Node.prototype.insertAfter = function(n,r) {this.insertBefore(n,r.nextSibling);};
/**
* Initialize Plugin
* @public
* @param {Object} options User settings
*/
priorityNav.init = function (options) {
// Feature test.
if (!supports){
console.warn("This browser doesn't support priorityNav");
return;
}
/**
* Merge user options with defaults
* @type {Object}
*/
settings = extend(defaults, options || {});
/**
* Store nodes
* @type {NodeList}
*/
var elements = document.querySelectorAll(settings.mainNavWrapper);
/**
* Loop over every instance and reference _this
*/
forEach(elements, function(_this){
/**
* Create breaks array
* @type {number}
*/
breaks[count] = [];
/**
* Set the instance number as data attribute
*/
_this.setAttribute("instance", count++);
/**
* Store the wrapper element
*/
mainNavWrapper = _this;
if (!mainNavWrapper) {
console.warn("couldn't find the specified mainNavWrapper element");
return;
}
/**
* Store the menu elementStore the menu element
*/
mainNav = settings.mainNav;
if (!_this.querySelector(mainNav)) {
console.warn("couldn't find the specified mainNav element");
return;
}
/**
* Check if we need to create the dropdown elements
*/
prepareHtml(_this);
/**
* Store the dropdown element
*/
navDropdown = settings.navDropdown;
if (!_this.querySelector(navDropdown)) {
console.warn("couldn't find the specified navDropdown element");
return;
}
/**
* Store the dropdown toggle element
*/
navDropdownToggle = settings.navDropdownToggle;
if (!_this.querySelector(navDropdownToggle)) {
console.warn("couldn't find the specified navDropdownToggle element");
return;
}
/**
* Event listeners
*/
listeners(_this);
/**
* Start first check
*/
priorityNav.doesItFit(_this);
});
/**
* Count amount of instances
*/
instance++;
/**
* Add class to HTML element to activate conditional CSS
*/
document.documentElement.classList.add(settings.initClass);
};
/**
* Public APIs
*/
return priorityNav;
});