-
Notifications
You must be signed in to change notification settings - Fork 1
/
selecty.js
executable file
·475 lines (413 loc) · 13.3 KB
/
selecty.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
(function () {
'use strict';
// common function which is often using
var commonUse = {
/**
* [Add class to element]
*
* @param el {Object} -- element.
* @param cls {String} -- classes.
*/
addClass: function(el, cls) {
var elClass = el.className;
var blank = (elClass !== '') ? ' ' : '';
var added = elClass + blank + cls;
el.className = added;
},
/**
* [Remove class from element]
*
* @param el {Object} -- element.
* @param cls {String} -- classes.
*/
removeClass: function(el, cls) {
var elClass = ' '+el.className+' ';
elClass = elClass.replace(/(\s+)/gi, ' ');
var removed = elClass.replace(' '+cls+' ', ' ');
removed = removed.replace(/(^\s+)|(\s+$)/g, '');
el.className = removed;
},
/**
* [if element has some class]
*
* @param el {Object} -- element.
* @param cls {String} -- classes.
*
* @return {Boolean} -- true or false.
*/
hasClass: function(el, cls) {
var elClass = el.className;
var elClassList = elClass.split(/\s+/);
var x = 0;
for(x in elClassList) {
if(elClassList[x] == cls) {
return true;
}
}
return false;
},
/**
* [add event to some element, dom0, dom1, supports fuck ie]
*
* @param el {Object} -- element.
* @param type {String} -- event type, such as 'click', 'mouseover'.
* @param func {Function} -- function.
*
*/
addEvent: function(el, type, func) {
if(el.addEventListener) {
el.addEventListener(type, func, false);
} else if(el.attachEvent){
el.attachEvent('on' + type, func);
} else{
el['on' + type] = func;
}
},
/**
* [remove event to some element, dom0, dom1, supports fuck ie]
*
* @param el {Object} -- element.
* @param type {String} -- event type, such as 'click', 'mouseover'.
* @param func {Function} -- function.
*
*/
removeEvent: function(el, type, func) {
if (el.removeEventListener){
el.removeEventListener(type, func, false);
} else if (el.detachEvent){
el.detachEvent('on' + type, func);
} else {
delete el['on' + type];
}
},
/**
* [Remove element node]
*
* @param el {Object} -- element.
*
*/
removeElement: function(el) {
(el && el.parentNode) && el.parentNode.removeChild(el);
},
/**
* [Set unique id]
*
* @param prefix {String} -- id prefix name.
*
* @return {String}
*/
setUid: function(prefix) {
do prefix += Math.floor(Math.random() * 1000000);
while (document.getElementById(prefix));
return prefix;
},
/**
* [clone object]
*
* @param oldObj {Object} -- old object need to be cloned
*
* @return {Object} -- cloned object
*/
clone:function (oldObj) {
if (typeof(oldObj) != 'object') return oldObj;
if (oldObj === null) return oldObj;
var newObj = {};
for (var i in oldObj)
newObj[i] = commonUse.clone(oldObj[i]);
return newObj;
},
/**
* [extend object]
*
* @return {Object}
*/
extend: function() {
var args = arguments;
if (args.length < 1) return;
var temp = this.clone(args[0]);
for (var n = 1; n < args.length; n++) {
for (var i in args[n]) {
temp[i] = args[n][i];
}
}
return temp;
},
/**
* [event handler for ie8]
*
* @return {Object} ev: event; target: event.target
*/
eventHandler: function(e) {
var ev = e || window.event;
var target = ev.target || ev.srcElement;
return {
ev: ev,
target: target
};
},
/**
* [event stopPropagation for ie8]
*
*/
stopPropagation: function(e) {
if (e.stopPropagation) {
e.stopPropagation();
} else if (window.event) {
window.event.cancelBubble = true;
}
},
/**
* [Get element offset postion, like jQuery `$el.offset()`;]
*
* @param el {Object} -- element.
*
* @return {Object} -- top and left
*/
getOffset: function(el) {
var box = el.getBoundingClientRect();
return {
top: box.top + window.pageYOffset - document.documentElement.clientTop,
left: box.left + window.pageXOffset - document.documentElement.clientLeft
};
}
};
var Selecty = function(el, opts) {
if (!(this instanceof Selecty)) return new Selecty(el, opts);
this.settings = commonUse.extend({}, this.defaults, opts);
this.el = el;
this.multiple = false;
this.selected = []; // cache option has been selected array
this.shown = false;
this.disabled = false; // is <select> disabled
this.ul = null; // cache ul element
this.optionLi = []; // cache option li, not include optgroup li
this.items = null; // cache <option> and <optgroup>
this.options = null; // cache original options
this.template = '<div class="selecty">'+
'<a class="selecty-selected"></a>'+
'<ul class="selecty-options"></ul>'+
'</div>';
this.init(el);
};
Selecty.prototype = {
defaults: {
separator: ', '
},
/**
* [selecty init]
*
* @param el {Object} -- element to call selecty.
*/
init: function(el) {
// handle call if use '#id'
if (typeof el === 'string' && el[0] === '#') {
el = document.getElementById(el.substr(1));
this.el = el;
}
// if element is not given
if(!el) {
console.error('Need select element!');
return;
}
// handle if <select> has no options
if (el.length < 1) {
console.error('No options inside <select>');
return;
}
if (this.el.getAttributeNode('multiple') !== null) {
this.multiple = true;
}
// just build for <select>
el.nodeName === 'SELECT' && this.build();
},
/**
* [generate fake select]
*
*/
build: function() {
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
this.el.classList.add('selecty-select');
var arrow = document.createElement('div');
arrow.classList.add('selecty-arrow');
arrow.style.top = commonUse.getOffset(this.el).top + this.el.offsetHeight/2 + 'px';
arrow.style.right = commonUse.getOffset(this.el).left + 'px';
this.el.parentNode.insertBefore(arrow, arrow.nextSibling);
return;
}
this.el.style.display = 'none'; // hide original <select>
this.options = this.el.querySelectorAll('option');
this.items = this.el.querySelectorAll('option, optgroup');
if (this.el.getAttributeNode('disabled') !== null) this.disabled = true;
// inject html
var $dropdown = document.createElement('div');
$dropdown.innerHTML = this.template;
var $wrapper = $dropdown.querySelector('.selecty');
if (this.disabled) commonUse.addClass($wrapper, 'disabled');
this.btn = $dropdown.querySelector('.selecty-selected');
this.ul = $dropdown.querySelector('.selecty-options');
var optionIndex = -1; // for use to set <li data-index='?'>
var isOptgroup = false;
// original option to selecty box
for (var i = 0; i < this.items.length; i++) {
optionIndex++;
var $li = document.createElement('li');
if (this.items[i].nodeName === 'OPTGROUP') {
optionIndex--;
isOptgroup = true;
$li.innerHTML = this.items[i].getAttribute('label');
commonUse.addClass($li, 'optgroup');
} else {
$li.innerHTML = this.items[i].innerHTML; // original <option> to li
$li.setAttribute('data-value', this.items[i].value); // original value to li
$li.setAttribute('data-index', optionIndex); // original index to li
isOptgroup && commonUse.addClass($li, 'optgroup-option');
if (this.items[i].getAttributeNode('selected') !== null) {
this.selected.push(optionIndex); // selected to cache array
commonUse.addClass($li, 'selected');
}
if (this.items[i].getAttributeNode('disabled') !== null) {
commonUse.addClass($li, 'disabled');
}
}
this.ul.appendChild($li);
}
this.optionLi = this.ul.querySelectorAll('li[data-index]');
this.updateSelected();
this.el.parentNode.insertBefore($dropdown.firstChild, this.el.nextSibling); // insert html
this.events();
},
events: function() {
if(this.disabled) return;
var that = this;
commonUse.addEvent(that.btn, 'click', function(e) {
// close other selety if it has been showned
var others = that.otherActived();
if (others !== null) {
commonUse.removeClass(others, 'active');
}
commonUse.stopPropagation(e);
that.show();
commonUse.addEvent(document, 'click', bodyClick);
});
commonUse.addEvent(document, 'keydown', function(e) {
if (e.which == 27) that.hide(); // ESC hide options
});
var bodyClick = function(e) {
var target = commonUse.eventHandler(e).target;
var targetIndex = parseInt(target.getAttribute('data-index'));
var isOptgroup = commonUse.hasClass(target, 'optgroup');
if (isOptgroup) return; // do noting if click optgroup li
if (target.nodeName === 'LI' && targetIndex !== null) {
if (commonUse.hasClass(target, 'disabled')) return;
if (that.multiple) {
if (commonUse.hasClass(target, 'selected')) {
that.selected.splice(that.selected.indexOf(targetIndex), 1); // remove clicked index from selected cache
} else {
that.selected.push(targetIndex); // add click index to selected cache
}
that.updateSelected();
} else {
that.selected = []; // empty cache selected index
that.selected.push(targetIndex); // push clicked index to cache selected
that.updateSelected();
that.hide();
commonUse.removeEvent(document, 'click', bodyClick);
}
} else {
that.hide();
commonUse.removeEvent(document, 'click', bodyClick);
}
};
},
/**
* [show options]
*
*/
show: function() {
commonUse.addClass(this.ul, 'active'); // show selecty options
this.shown = true;
},
/**
* [hide options]
*
*/
hide: function() {
commonUse.removeClass(this.ul, 'active');
commonUse.removeEvent(document.body, 'click', function(e){});
this.shown = false;
},
/**
* [get actived selecty element for closing it]
*
*/
otherActived: function() {
var allSelecty = document.body.querySelectorAll('.selecty-options');
for (var i = 0; i < allSelecty.length; i++) {
if (commonUse.hasClass(allSelecty[i], 'active')) {
return allSelecty[i];
}
}
return null;
},
/**
* [update selected option]
*
*/
updateSelected: function() {
this.clearSelected();
this.btn.innerHTML = ''; // empty btn's html
// sort selected index asend
this.selected.sort(function(a, b){
return a-b;
});
for (var i = 0; i < this.selected.length; i++) {
var selectedIndex = this.selected[i];
this.options[selectedIndex].setAttribute('selected', 'selected');
commonUse.addClass(this.optionLi[selectedIndex], 'selected');
if (this.multiple) { // multiple
var divide = this.settings.separator; // get selected text divide
if(this.btn.innerHTML === '') divide = '';
this.btn.innerHTML += divide+this.options[selectedIndex].innerHTML;
} else {
this.btn.innerHTML = this.options[selectedIndex].innerHTML;
}
}
if(this.btn.innerHTML === '') this.btn.innerHTML = this.options[0].innerHTML; // default set first option to btn html
},
/**
* [clear all selected option, including original <option> and new <li>]
*
*/
clearSelected: function() {
for (var i = 0; i < this.options.length; i++) {
this.options[i].removeAttribute('selected');
commonUse.removeClass(this.optionLi[i], 'selected');
}
}
};
// NPM, AMD, and wndow support
if ('undefined' !== typeof module && !! module && !! module.exports) {
module.exports = Selecty;
} else if (typeof define === 'function' && define.amd) {
define([], function() {
return Selecty;
});
} else {
window.selecty = Selecty;
}
var jQuery = window.jQuery;
// Support jQuery
if (jQuery !== undefined) {
jQuery.fn.selecty = function () {
var args = Array.prototype.slice.call(arguments);
return jQuery(this).each( function() {
if (!args[0] || typeof args[0] === 'object') {
new Selecty(this, args[0] || {});
} else if (typeof args[0] === 'string') {
Selecty.prototype[args[0]].apply(new Selecty(this), args.slice(1));
}
});
};
}
}());