forked from BMSVieira/BVSelect-VanillaJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbvselect.js
More file actions
525 lines (438 loc) · 23.8 KB
/
bvselect.js
File metadata and controls
525 lines (438 loc) · 23.8 KB
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
/*-------------------------
BVSelect - Vanilla Javascript Fully Customizable SelectBox v1.3
https://github.com/BMSVieira/BVSelect-VanillaJS
Made by: Bruno Vieira
--------------------------- */
class BVSelect {
constructor({
selector = 'defaultId',
width = "100%",
searchbox = false,
search_autofocus = false,
offset = true,
search_placeholder = "Search...",
placeholder = "Select Option",
breakpoint = "600"
})
{
// Random Number generated
var randomID = Math.floor(Math.random() * (9999 - 0 + 1)) + 0;
var SearchPlaceholder = search_placeholder;
var MainPlaceholder = placeholder;
var selectedIDFocus = 0; // Save wich dropdown is currently open
var selectedMultiple = [];
var selected_option_text = "";
var first_option_text = "";
var MDivSelector = selector.substring(1);
// Define Variables
this.selector = selector.substring(1);
this.searchbox = searchbox;
this.width = width;
this.offset = offset;
this.randomID = randomID;
this.search_placeholder;
this.breakpoint = breakpoint;
this.search_autofocus = search_autofocus;
// Hides native selector
document.getElementById(this.selector).style.display = "none";
// ** ADD OPTIONS TO LIST **
this.SetupListOptions = function() {
// Get All options inside Selectbox
var x = document.getElementById(this.selector);
for (var i = 0; i < x.length; i++) {
var optionText = x[i].text;
var optionValue = x[i].value;
var optionDisabled = x[i].disabled;
var optionSeparator = x[i].getAttribute("data-separator");
var optionImg = x[i].getAttribute("data-img");
var optionIcon = x[i].getAttribute("data-icon");
// Option Disabled
if (optionDisabled == true) {
var is_disabled = "bv_disabled";
} else {
var is_disabled = "";
}
// Separator
if (optionSeparator) {
var is_separator = "bv_separator";
} else {
var is_separator = "";
}
// Check for Attachment
if (optionImg) {
var has_attachment = "<img src=" + optionImg + ">";
} else {
if (optionIcon) {
var has_attachment = "<i class='" + optionIcon + "' aria-hidden='true'></i>";
} else {
var has_attachment = "";
}
}
// Append
document.getElementById("ul_" + randomID).insertAdjacentHTML('beforeend', "<li class='" + is_disabled + " " + is_separator + "' > " + has_attachment + " " + optionText + "</li>");
}
document.querySelectorAll('#ul_' + randomID + ' li').forEach((item) => {
item.addEventListener('click', (e) => {
const index = Array.from(item.parentNode.children).indexOf((item))
var selected_option = document.getElementById(this.selector);
if (this.searchbox == true) {
var numberless = -1;
} else {
var numberless = "";
}
if (item.classList.contains("bv_disabled") || item.classList.contains("nofocus") || item.classList.contains("bv_separator")) {} else {
if (selected_option.attributes.multiple) {
var SelectedNames = "";
event.preventDefault();
if (selectedMultiple.indexOf(index) > -1) {
var index_test = selectedMultiple.indexOf(index);
selectedMultiple.splice(index_test, 1);
document.getElementById(this.selector)[index + numberless].selected = false;
item.style.backgroundColor = "transparent";
} else {
selectedMultiple.push(index);
item.style.backgroundColor = "#ececec";
} // Adds to array
// Check if array is empty, if it is, gets the first option
if (selectedMultiple.length == 0) {
SelectedNames = MainPlaceholder;
} else {
for (var i = 0; i < selectedMultiple.length; i++) {
var indexValFromArray = selectedMultiple[i];
document.getElementById(this.selector).getElementsByTagName('option')[indexValFromArray + numberless].selected = 'selected';
SelectedNames += ", " + selected_option[indexValFromArray - 1].innerHTML;
}
SelectedNames = SelectedNames.substring(2);
}
// Adds the texto o the main DIV
document.getElementById("main_" + randomID).innerHTML = SelectedNames + "<i id='arrow_" + randomID + "' class='arrows_bv arrow down'></i>";
} else {
// Get Index of option
document.getElementById(this.selector).getElementsByTagName('option')[index + numberless].selected = 'selected';
// Trigger onchange function
if (x.getAttribute("onchange") != null) {
document.getElementById(this.selector).onchange();
}
// Updates main div
document.getElementById("main_" + randomID).innerHTML = item.textContent + "<i id='arrow_" + randomID + "' class='arrows_bv arrow down'></i>";
document.getElementById("ul_" + randomID).style.display = "none";
// Remove class so Body has Scroll Again
document.body.classList.remove("stop-scrolling");
if(document.body.contains(document.getElementById('deletebg'))){
document.getElementById("deletebg").remove();
}
FixVerticalViewPort();
}
// When click, resets search filter
if (this.searchbox == true) {
document.getElementById("input_" + randomID).value = "";
Array.from(document.querySelectorAll("#ul_" + randomID + " li")).forEach(function(val) {
val.style.display = "block";
});
}
}
})
});
}
// ** CREATE MAIN **
this.CriarDivBase = function() {
document.getElementById(this.selector).insertAdjacentHTML('afterend', '<div id="bv_' + randomID + '" data-search="' + this.searchbox + '" class="bv_mainselect"></div>');
document.getElementById("bv_" + randomID).insertAdjacentHTML('afterbegin', '<div id="main_' + randomID + '" style="width:' + this.width + ';" class="bv_atual bv_background"></div><ul id="ul_' + randomID + '" class="bv_ul_inner bv_background"></ul>');
var element_ul = document.getElementById('ul_' + randomID);
var element_bv = document.getElementById('bv_' + randomID);
// Set Width of UL
var select_width = document.getElementById("main_" + randomID).offsetWidth;
element_ul.style.width = select_width + "px";
if (this.searchbox == true) {
document.querySelector("#ul_" + randomID).insertAdjacentHTML('afterbegin', '<li class="nofocus"><div class="innerinput"><input placeholder="' + SearchPlaceholder + '" class="bv_input" id="input_' + randomID + '" type="text"></div</li>');
}
// Get Selected Option
var selected_option = document.getElementById(this.selector);
if (!selected_option.attributes.multiple) {
// Check if exists any selected option in the native selectbox
for (var i = 0; i < selected_option.length; i++) {
if (selected_option[i].getAttribute("selected") == "") {
var FoundSelectedOP = 1;
}
}
// if is 1, its because found it, if not get the placeholder.
if (FoundSelectedOP == 1) {
first_option_text = selected_option.options[selected_option.selectedIndex].text;
} else {
first_option_text = MainPlaceholder;
}
} else {
// Se for multiple, vai buscar sempre o placeholder
first_option_text = MainPlaceholder;
}
document.getElementById("main_" + randomID).innerHTML = first_option_text + "<i id='arrow_" + randomID + "' class='arrows_bv arrow down'></i>";
// Add event Listener on click main div
document.getElementById("main_" + randomID).addEventListener("click", function() {
// Reset dropdown position, in case it was changed before
document.getElementById("ul_" + randomID).style.position = "absolute";
document.getElementById("ul_" + randomID).style.bottom = "";
// Check Windows Width for Mobile
if(window.innerWidth < breakpoint)
{
document.getElementById("ul_" + randomID).classList.add("bv_ul_mobile");
document.getElementById(MDivSelector).insertAdjacentHTML('afterend', '<div id="deletebg" class="bv_ul_bg"></div>');
document.body.classList.add("stop-scrolling");
} else {
document.getElementById("ul_" + randomID).classList.remove("bv_ul_mobile");
}
// Correct the width of the UL when window is resized
var select_width = document.getElementById("main_" + randomID).offsetWidth;
element_ul.style.width = select_width + "px";
if (document.getElementById('ul_' + randomID).style.display == 'block') {
document.getElementById('ul_' + randomID).style.display = 'none';
Array.from(document.querySelectorAll(".arrows_bv"))
.forEach(function(val) {
val.classList.remove("up");
val.classList.add("down");
});
} else {
Array.from(document.querySelectorAll(".bv_ul_inner"))
.forEach(function(val) {
val.style.display = 'none';
});
BVfadeIn(document.getElementById('ul_' + randomID));
Array.from(document.querySelectorAll(".arrows_bv"))
.forEach(function(val) {
val.classList.remove("up");
val.classList.add("down");
});
document.querySelector("#arrow_" + randomID).classList.remove("down");
document.querySelector("#arrow_" + randomID).classList.add("up");
}
// Call function at end of the dropdown movement
if (offset == true) { FixVerticalViewPort(); }
// Check if autofocus and search is enabled
if(search_autofocus == true && searchbox == true) { document.getElementById("input_" + randomID).focus();}
}, false);
// ** SETUP LIST OPTIONS **
this.SetupListOptions();
}
// ** CREATES MAIN DIV **
this.CriarDivBase();
// ** ON SCROLL EVENT TO PREVENT OUT OF VIEWPORT **
document.addEventListener("scroll", function() {
if (selectedIDFocus != 0) {
var currentWindowViewOffSet = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
var container = document.getElementById("main_" + randomID);
var lastchild = container.lastChild;
var currentElementViewOffSet = lastchild.getBoundingClientRect().top;
var MainDivOff = document.getElementById("ul_" + randomID).clientHeight;
var DiffBetW = currentWindowViewOffSet - currentElementViewOffSet // Difference between Element and Window
// If Difference is greater than List's height
if (DiffBetW > MainDivOff) {
FixVerticalViewPort();
}
}
}, false);
// ** FADE OUT FUNCTION **
function BVfadeOut(el) {
el.style.opacity = 1;
(function fade() {
if ((el.style.opacity -= .1) < 0) {
el.style.display = "none";
} else {
requestAnimationFrame(fade);
}
})();
};
// ** FADE IN FUNCTION **
function BVfadeIn(el, display) {
el.style.opacity = 0;
el.style.display = display || "block";
(function fade() {
var val = parseFloat(el.style.opacity);
if (!((val += .1) > 1)) {
el.style.opacity = val;
requestAnimationFrame(fade);
}
})();
};
// ** CHECK VIEW PORT OFFSET **
function FixVerticalViewPort() {
var currentWindowView = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
var container = document.getElementById("ul_" + randomID);
var lastchild = container.lastChild;
var currentElementView = lastchild.getBoundingClientRect().top;
// +50 to fix outer border
if (Math.round(currentElementView + 50) > Math.round(currentWindowView)) {
selectedIDFocus = randomID;
document.getElementById("ul_" + randomID).style.position = "fixed";
document.getElementById("ul_" + randomID).style.bottom = "0px";
} else {
selectedIDFocus = 0;
document.getElementById("ul_" + randomID).style.position = "absolute";
document.getElementById("ul_" + randomID).style.bottom = "";
}
}
// ** SEARCH BAR **
if (this.searchbox == true) {
document.getElementById("input_" + randomID).addEventListener("keyup", function() {
var input, filter, ul, li, i, txtValue;
input = document.getElementById("input_" + randomID);
filter = input.value.toUpperCase();
ul = document.getElementById("ul_" + randomID);
li = ul.getElementsByTagName("li");
// Hides all separators
Array.from(document.querySelectorAll(".bv_separator")).forEach(function(val) {
val.style.display = "none";
});
for (i = 0; i < li.length; i++) {
// If Empty, appears every line
if (filter == "") {
Array.from(document.querySelectorAll("#ul_" + randomID + " li")).forEach(function(val) {
val.style.display = "block";
});
} else {
// Removes separators from search
txtValue = li[i].innerText || li[i].textContent;
if (txtValue.toUpperCase().indexOf(filter) > -1 && !li[i].classList.contains("bv_separator")) {
li[i].style.display = "";
} else {
if (!li[i].classList.contains("nofocus")) {
li[i].style.display = "none";
}
}
}
}
}, false);
}
// ** CLICK OUTSIDE **
document.addEventListener("click", function(e) {
if (!e.target.closest(".bv_ul_inner") || !event.target.classList.contains('bv_input')) {
if (!event.target.classList.contains('bv_input') && !event.target.classList.contains('bv_atual')) {
if (event.target.nodeName != "LI") {
Array.from(document.querySelectorAll(".bv_ul_inner"))
.forEach(function(val) {
val.style.display = 'none';
});
Array.from(document.querySelectorAll(".arrows_bv"))
.forEach(function(val) {
val.classList.remove("up");
val.classList.add("down");
});
// When click outside, resets search filter
Array.from(document.querySelectorAll("#input_" + randomID)).forEach(function(val) {
val.value = "";
});
Array.from(document.querySelectorAll("#ul_" + randomID + " li")).forEach(function(val) {
val.style.display = "block";
});
// Remove class so Body has Scroll Again
document.body.classList.remove("stop-scrolling");
if(document.body.contains(document.getElementById('deletebg'))){
document.getElementById("deletebg").remove();
}
if (document.getElementById("ul_" + randomID)) // Checks if element existed in case it was destroyed
{
selectedIDFocus = 0;
document.getElementById("ul_" + randomID).style.position = "absolute";
document.getElementById("ul_" + randomID).style.bottom = "";
}
}
}
}
}, true);
}
// ** METHODS **
// DESTROY
Destroy() {
// Destroy main element and shows up native selectbox
document.getElementById("bv_" + this.randomID).remove();
document.getElementById(this.selector).style.display = "block";
}
// UPDATE
Update() {
// Removes all Li that does not contain class "nofocus" - Its the search.
Array.from(document.querySelectorAll("#ul_" + this.randomID + " li"))
.forEach(function(val) {
if (!val.classList.contains("nofocus")) {
val.remove();
}
});
this.SetupListOptions();
}
// GET ID
GetID() {
// Return ID Generated when building Dropdown, so you can add custom classes
return this.randomID;
}
// CHANGE
Change(properties) {
if(properties.placeholder)
{
document.getElementById("main_" + this.randomID).innerHTML = properties.placeholder + "<i id='arrow_" + this.randomID + "' class='arrows_bv arrow down'></i>";
}
if(properties.search_placeholder)
{
document.getElementById("input_" + this.randomID).placeholder = properties.search_placeholder;
}
if(properties.options && typeof(properties.options) === 'object')
{
// Clean every option inside the original selector
document.querySelector("#"+this.selector).innerHTML = "";
// Loop object and add new options to original select box
var prop = Object.keys(properties.options).length;
for (var i = 0; i < prop; i++) {
var change_disabled, change_separator, change_img, change_icon;
if(properties.options[i].disabled == true){ change_disabled = "disabled"; } else { change_disabled = ""; }
if(properties.options[i].separator == true){ change_separator = "data-separator='true'"; } else { change_separator = ""; }
if(properties.options[i].img){ change_img = "data-img='"+properties.options[i].img+"'"; } else { change_img = ""; }
if(properties.options[i].icon){ change_icon = "data-icon='"+properties.options[i].icon+"'"; } else { change_icon = ""; }
document.getElementById(this.selector).insertAdjacentHTML('beforeend', "<option "+change_img+" "+change_icon+" "+change_separator+" "+change_disabled+" value="+properties.options[i].value+" >"+properties.options[i].inner_text+"</option>");
}
} else {
console.error("Options must be and Object. Read documentation.");
}
}
// Set option
SetOption(properties) {
var selectorIndex = document.getElementById(this.selector);
// If is set by index
if(properties.type == "byIndex")
{
selectorIndex.selectedIndex = properties.value;
// Trigger onchange function
if (selectorIndex.getAttribute("onchange") != null) { document.getElementById(this.selector).onchange(); }
document.getElementById("main_" + this.randomID).innerHTML = selectorIndex.options[selectorIndex.selectedIndex].text + "<i id='arrow_" + this.randomID + "' class='arrows_bv arrow down'></i>";
// if is set by value
} else if(properties.type == "byValue")
{
for (var i = 0; i < selectorIndex.length; i++) {
if(selectorIndex[i].value == properties.value)
{
selectorIndex.selectedIndex = selectorIndex[i].index;
// Trigger onchange function
if (selectorIndex.getAttribute("onchange") != null) { document.getElementById(this.selector).onchange(); }
document.getElementById("main_" + this.randomID).innerHTML = selectorIndex[i].innerText + "<i id='arrow_" + this.randomID + "' class='arrows_bv arrow down'></i>";
}
}
}
}
// Append/Prepend Option
AppendOption(properties) {
console.log(properties);
// Get position e check if position is undefined.
var position = properties.position;
if(position == undefined) { var position = "beforeend"; }
if(properties.options && typeof(properties.options) === 'object')
{
// Loop object and add new options to original select box
var prop = Object.keys(properties.options).length;
for (var i = 0; i < prop; i++) {
var change_disabled, change_separator, change_img, change_icon;
if(properties.options[i].disabled == true){ change_disabled = "disabled"; } else { change_disabled = ""; }
if(properties.options[i].separator == true){ change_separator = "data-separator='true'"; } else { change_separator = ""; }
if(properties.options[i].img){ change_img = "data-img='"+properties.options[i].img+"'"; } else { change_img = ""; }
if(properties.options[i].icon){ change_icon = "data-icon='"+properties.options[i].icon+"'"; } else { change_icon = ""; }
document.getElementById(this.selector).insertAdjacentHTML(position, "<option "+change_img+" "+change_icon+" "+change_separator+" "+change_disabled+" value="+properties.options[i].value+" >"+properties.options[i].inner_text+"</option>");
}
} else {
console.error("Options must be and Object. Read documentation.");
}
}
}