-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlc_select.js
More file actions
1181 lines (939 loc) · 43.9 KB
/
Copy pathlc_select.js
File metadata and controls
1181 lines (939 loc) · 43.9 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
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* lc_select.js - Superlight Javascript dropdowns
* Version: 1.3.0
* Author: Luca Montanari (LCweb)
* Website: https://lcweb.it
* Licensed under the MIT license
*/
(function() {
"use strict";
if(typeof(window.lc_select) != 'undefined') {return false;} // prevent multiple script inits
/*** vars ***/
let debounced_vars = [],
noscroll_window = false,
style_generated = null,
active_trigger = null;
/*** default options ***/
const def_opts = {
enable_search : true, // (bool) whether to enable fields search
min_for_search : 7, // (int) minimum options number to show search
autofocus_search: false, // (bool) whether to automatically focus search field on desktop (NB: will break tabindex chain)
wrap_width : 'auto', // (string) defines the wrapper width: "auto" to leave it up to CSS, "inherit" to statically copy input field width, or any other CSS sizing
addit_classes : [], // (array) custom classes assigned to the field wrapper (.lcslt-wrap) and dropdown (#lc-select-dd)
pre_placeh_opt : false, // (bool) if true, on simple dropdowns without a selected value, prepend an empty option using placeholder text
max_opts : false, // (int|false) defining maximum selectable options for multi-select
on_change : null, // function(new_value, target_field) {}, - triggered every time field value changes. Passes value and target field object as parameters
labels : [ // (array) option used to translate script texts
'search options',
'add options',
'Select options ..',
'.. no matching options ..',
],
};
/*** hide dropdown cicking outside ***/
document.addEventListener('click', function(e) {
const dd = document.querySelector("#lc-select-dd.lcslt-shown");
if(!dd) {
return true;
}
// is an element within a trigger?
for (const trigger of document.getElementsByClassName('lcslt-wrap')) {
if(trigger.contains(e.target)) {
return true;
}
}
// close if clicked element is not in the dropdown
if(!dd.contains(e.target) && !e.target.classList.contains('lcslt-shown')) {
dd.remove();
if(active_trigger) {
active_trigger.classList.remove('lcslt_dd-open');
active_trigger = null;
}
}
return true;
});
/* hide dropdown on screen resizing */
window.addEventListener('resize', function(e) {
const dd = document.querySelector("#lc-select-dd.lcslt-shown");
if(!dd) {
return true;
}
// avoid closing if on mobile and searching
if(document.activeElement.hasAttribute('type') && document.activeElement.getAttribute('type') === 'text') {
return true;
}
dd.classList.remove('lcslt-shown');
active_trigger.classList.remove('lcslt_dd-open');
active_trigger = null;
return true;
});
// disable page scroll on element scroll
window.addEventListener('scroll', (e) => {
if(document.querySelector('.lc-select-dd-scroll') && noscroll_window) {
window.scrollTo(noscroll_window[0], noscroll_window[1]);
}
});
/* navigate through dd opts with keys (38 up, 40 down, 13 enter, 27 exit, 9 tab)*/
document.addEventListener("keydown", (e) => {
if([38, 40, 13, 27, 9].indexOf(e.keyCode) === -1 || !document.querySelector("#lc-select-dd.lcslt-shown")) {
return true;
}
e.preventDefault();
const highlighted = document.querySelector(".lcslt-dd-opt.lcslt-dd-opt-hlight"),
opts = document.querySelectorAll(".lcslt-dd-opt:not(.lcslt-disabled)"),
event = new Event('mouseenter', {bubbles:true});
switch(e.keyCode) {
case 27 : // close
active_trigger.click();
break;
case 9 : // tab
if(!document.activeElement.classList || !document.activeElement.classList.contains('lcslt-tabindex-trick')) {
active_trigger.click();
}
break;
case 13 : // select
if(highlighted) {
highlighted.classList.remove('lcslt-dd-opt-hlight');
highlighted.click();
}
break;
case 38 : // up
case 40 : // down
let sel_index = (e.keyCode == 38) ? 0 : opts.length - 1; // by default set to first or last element
if(highlighted) {
opts.forEach((opt, i) => {
if(opt == highlighted) {
sel_index = i;
}
});
}
let new_sel;
if(e.keyCode == 38) {
new_sel = (!sel_index) ? opts.length - 1 : sel_index - 1;
} else {
new_sel = (sel_index == (opts.length - 1)) ? 0 : sel_index + 1;
}
opts[new_sel].dispatchEvent(event);
set_hlight_opt_scroll();
break;
}
return true;
});
/* set dropdown scroll position for highlighted option */
const set_hlight_opt_scroll = () => {
const hlight = document.querySelector('.lcslt-dd-opt-hlight');
if(!hlight) {
return false;
}
const top_border = parseInt(getComputedStyle(hlight)['borderTopWidth'], 10);
document.querySelector(".lc-select-dd-scroll").scrollTop = hlight.offsetTop - ((hlight.offsetHeight + top_border) * 2) - 10;
};
/*** plugin class ***/
window.lc_select = function(attachTo, options = {}) {
if(!attachTo) {
return console.error('You must provide a valid selector or DOM object as first argument');
}
// override options
if(typeof(options) != 'object') {
return console.error('Options must be an object');
}
options = Object.assign({}, def_opts, options);
/* initialize */
this.init = function() {
const $this = this;
// Generate style
if(!style_generated) {
this.generate_style();
style_generated = true;
}
// assign to each target element
maybe_querySelectorAll(attachTo).forEach(function(el) {
if(el.tagName != 'SELECT') {
return;
}
// do not initialize twice
if(el.parentNode.classList.length && el.parentNode.classList.contains('lcslt-wrap')) {
return;
}
// do not initialize elements without name
/*if(!el.getAttribute('name')) {
return;
}*/
$this.wrap_element(el);
// hook to update LC select implementation of select fields (eg. when new fields are dynamically added)
el.removeEventListener('lc-select-refresh', () => {});
el.addEventListener('lc-select-refresh', (e) => {
// close eventually opened dropdowns
if(active_trigger) {
active_trigger.click();
}
const trigger = e.target.parentNode.querySelector('.lcslt');
$this.set_sel_content(trigger);
// only on initialized elements
if(!e.target.parentNode.classList.length || (e.target.parentNode.classList.length && !e.target.parentNode.classList.contains('lcslt-wrap'))) {
return false;
}
// track disabled status
(e.target.disabled) ? trigger.classList.add('lcslt-disabled') : trigger.classList.remove('lcslt-disabled');
return true;
});
// hook destroying LC select implementation of select fields
el.removeEventListener('lc-select-destroy', () => {});
el.addEventListener('lc-select-destroy', (e) => {
// close eventually opened dropdowns
if(active_trigger) {
active_trigger.click();
}
const select = e.target,
wrap = e.target.parentNode,
fake_opt = select.querySelector('option[data-lcslt-placeh="1"]');
// only on initialized elements
if(!wrap.classList.length || (wrap.classList.length && !wrap.classList.contains('lcslt-wrap'))) {
return false;
}
if(fake_opt) {
fake_opt.remove();
}
wrap.parentNode.insertBefore(select, wrap);
wrap.remove();
return true;
});
});
};
/* wrap target element to allow trigger display */
this.wrap_element = function(el) {
const $this = this,
div = document.createElement('div'),
fname_class = 'lcslt-f-'+ el.getAttribute('name').replace(/\[\]/g, ''),
disabled_class= (el.disabled) ? 'lcslt-disabled' : '',
multi_class = (el.multiple) ? 'lcslt-multiple' : '',
tabindex = (el.getAttribute('tabindex')) ? 'tabindex="'+ parseInt(el.getAttribute('tabindex'), 10) +'"' : '',
uniqueId = Math.random().toString(36).slice(2, 11);
// be sure there's a placeholder for multiple
let placeh = (el.hasAttribute('data-placeholder')) ? el.getAttribute('data-placeholder').trim() : '';
if(!placeh && multi_class) {
placeh = options.labels[2];
}
// escape placeholder value for safe usage in attributes
placeh = placeh
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// additional classes
if(typeof(options.addit_classes) == 'object') {
options.addit_classes.some((aclass) => {
div.classList.add( aclass );
});
}
// static width from select?
let dd_width;
if(options.wrap_width != 'auto') {
dd_width = (options.wrap_width == 'inherit') ? Math.round(el.getBoundingClientRect().width) + 'px' : options.wrap_width;
div.style.width = dd_width;
}
div.classList.add("lcslt-wrap", fname_class);
div.innerHTML = '<label for="'+ uniqueId +'" class="lcslt-displaynone">'+ fname_class +'</label>' +
'<input type="text" name="'+ fname_class +'-tit" '+ tabindex +' class="lcslt-tabindex-trick" id="'+ uniqueId +'" />' +
'<div class="lcslt '+ fname_class +' '+ multi_class +' '+ disabled_class +'" data-placeh="'+ placeh +'" role="button" tabindex="0"></div>';
el.parentNode.insertBefore(div, el);
div.appendChild(el);
// inherit width - count lc-select paddings
if(options.wrap_width == 'inherit') {
const $lcslt = div.querySelector('.lcslt'),
lcslt_style = $lcslt.currentStyle || window.getComputedStyle($lcslt);
let addit_w = parseInt(lcslt_style.paddingRight, 10) + parseInt(lcslt_style.paddingLeft, 10);
// is there any image? count it
if(el.querySelector('option[data-image]')) {
addit_w = addit_w + 20;
}
div.style.width = (parseInt(dd_width, 10) + addit_w) +'px';
}
const trigger = div.querySelector('.lcslt');
// simple dropdown placeholder
if(options.pre_placeh_opt && !multi_class && placeh) {
// be sure no other option is selected
let no_selected = true;
el.querySelectorAll('option').forEach(opt => {
if(opt.hasAttribute('selected')) {
no_selected = false;
return false;
}
});
if(no_selected) {
const ph_opt = document.createElement('option');
ph_opt.setAttribute('data-lcslt-placeh', 1);
ph_opt.setAttribute('value', "");
ph_opt.style.display = 'none';
ph_opt.innerHTML = placeh;
ph_opt.selected = true;
el.insertBefore(ph_opt, el.firstChild);
}
}
// set content
this.set_sel_content(trigger);
// event to show dropdown
trigger.addEventListener("click", (e) => {
if(
!trigger.classList.contains('lcslt-disabled') &&
!e.target.classList.contains('lcslt-multi-selected') &&
!e.target.classList.contains('lcslt-max-opts') &&
!e.target.parentNode.classList.contains('lcslt-multi-selected')
) {
$this.show_dd(trigger)
}
});
// tabindex focus trick
div.querySelector('.lcslt-tabindex-trick').onfocus = (e) => {
trigger.click();
};
};
/* Set selected content into .lcslt */
this.set_sel_content = function(trigger = false) {
if(!trigger) {
trigger = active_trigger;
}
const $this = this,
select = trigger.nextSibling,
is_multiple = trigger.classList.contains('lcslt-multiple');
let code = '',
tot_opts = 0,
sel_opts = 0;
select.querySelectorAll('option').forEach(opt => {
if(opt.selected) {
const img = (opt.hasAttribute('data-image')) ? '<i class="lcslt-img" style="background-image: url(\''+ opt.getAttribute('data-image').trim() +'\')"></i>' : '';
if(is_multiple) {
code += '<div class="lcslt-multi-selected" role="button" data-val="'+ opt.getAttribute('value') +'" title="'+ opt.innerHTML +'"><span>'+ img + opt.innerHTML +'</span></div>';
}
else {
const single_placeh_mode = (options.pre_placeh_opt && opt.hasAttribute('data-lcslt-placeh')) ? 'class="lcslt-placeholder"' : '';
code = '<span '+ single_placeh_mode +' title="'+ opt.innerHTML +'">'+ img + opt.innerHTML +'</span>';
}
sel_opts++;
}
tot_opts++;
});
// max-values limit class management
let max_opts_reached = false;
if(typeof(options.max_opts) == 'number' && options.max_opts > 1) {
if(sel_opts >= options.max_opts) {
trigger.classList.add('lcslt-max-opts');
max_opts_reached = true;
}
else {
trigger.classList.remove('lcslt-max-opts')
}
}
// nothing selected? show placeholder
if(!code) {
code = '<span class="lcslt-placeholder">'+ trigger.getAttribute('data-placeh') +'</span>';
}
else if(is_multiple && tot_opts > sel_opts && !select.disabled && !max_opts_reached) {
code += '<span class="lcslt-multi-callout" role="button" title="'+ options.labels[1] +'">+</span>';
}
trigger.innerHTML = code;
// sel opt click listener - deselect
if(is_multiple) {
trigger.querySelectorAll('.lcslt-multi-selected').forEach(sel_opt => {
sel_opt.addEventListener("click", (e) => {
if( !recursive_parent(e.target, '.lcslt').classList.contains('lcslt-disabled') ) {
$this.deselect_option(e, trigger, sel_opt);
}
});
});
}
};
/* show dropdown */
this.show_dd = function(trigger) {
// close other opened dropdowns
if(document.querySelector("#lc-select-dd")) {
document.querySelector("#lc-select-dd").remove();
if(active_trigger) {
active_trigger.classList.remove('lcslt_dd-open');
}
}
// close if already opened
if(trigger == active_trigger) {
active_trigger = null;
return false;
}
active_trigger = trigger;
this.append_dd();
this.set_dd_position();
set_hlight_opt_scroll();
const $this = this,
dd = document.querySelector('#lc-select-dd');
dd.classList.add('lcslt-shown');
trigger.classList.add('lcslt_dd-open');
// be sure dropdown didn't add page scrollers. In case, adjust X pos
setTimeout(() => {
if(trigger.getBoundingClientRect().x != dd.getBoundingClientRect().x) {
$this.set_dd_position();
}
}, 10);
};
/* set dropdown position */
this.set_dd_position = function() {
if(!active_trigger) {
return;
}
const dd = document.querySelector('#lc-select-dd'),
select = active_trigger.parentNode.querySelector('select'),
at_offset = active_trigger.getBoundingClientRect(),
dd_w = at_offset.width.toFixed(2),
at_h = parseInt(active_trigger.clientHeight, 10) + parseInt(getComputedStyle(active_trigger)['borderTopWidth'], 10),
y_pos = parseInt(at_offset.y, 10) + parseInt(window.pageYOffset, 10) + at_h;
// left pos control - also checking side overflows
let left = at_offset.left.toFixed(2);
if(left < 0) {
left = 0;
}
dd.setAttribute('style', 'width:'+ dd_w +'px; top:'+ y_pos +'px; left: '+ left +'px;');
dd.setAttribute('data-fname', select.getAttribute('name'));
};
/* append and populates dropdown with select options */
this.append_dd = function() {
const $this = this,
select = active_trigger.parentNode.querySelector('select'),
highligh_set = false;
// var containing groups with options
let structure = new Map(),
/*
group_name : [map] {
opt_val : {
img : (string) ,
name : (string),
selected: (bool),
disabled: (bool)
}
}
*/
no_groups = false,
disabled_groups = [],
opts_order = [];
// retrieve groups
if(!select.querySelectorAll('optgroup').length) {
no_groups = true;
structure.set('%%ungrouped%%', new Map());
}
else {
select.querySelectorAll('optgroup').forEach(group => {
structure.set(group.getAttribute('label'), new Map());
if(group.disabled) {
disabled_groups.push( group.getAttribute('label') );
}
});
}
// retrieve options and preserve DOM order in opts_order
if(!structure.has('%%ungrouped%%')) {
structure.set('%%ungrouped%%', new Map());
}
// cycle through options and populate
[...select.children].forEach(child => {
if(child.tagName === 'OPTION') {
const val = child.getAttribute('value');
structure.get('%%ungrouped%%').set(val, {
img: (child.hasAttribute('data-image')) ? child.getAttribute('data-image').trim() : '',
name: child.innerHTML,
selected: child.selected,
disabled: child.disabled
});
// register as ungrouped in this case
opts_order.push({
type : 'option',
group: '%%ungrouped%%',
value: val
});
}
if(child.tagName === 'OPTGROUP') {
const label = child.getAttribute('label');
if(!structure.has(label)) {
structure.set(label, new Map());
}
if(child.disabled) {
disabled_groups.push(label);
}
// respect the order
opts_order.push({
type : 'group',
label: label
});
child.querySelectorAll('option').forEach(opt => {
structure.get(label).set(opt.getAttribute('value'), {
img: (opt.hasAttribute('data-image')) ? opt.getAttribute('data-image').trim() : '',
name: opt.innerHTML,
selected: opt.selected,
disabled: opt.disabled
});
});
}
});
/////
// prepare code
const multiple_class = (active_trigger.classList.contains('lcslt-multiple')) ? 'lcslt-multiple-dd' : '';
// additional classes
const addit_classes = (typeof(options.addit_classes) == 'object') ? options.addit_classes.join(' ') : '';
// build code
let code = '<div id="lc-select-dd" class="'+ multiple_class +' '+ addit_classes +'">';
// searchbar?
const has_searchbar = (options.enable_search && select.querySelectorAll('option').length >= parseInt(options.min_for_search, 10)) ? true : false;
if(has_searchbar) {
const uniqueId = Math.random().toString(36).slice(2, 11);
code +=
'<ul><li class="lcslt-search-li">' +
'<label for="'+ uniqueId +'" class="lcslt-displaynone">search</label>' +
'<input type="text" name="lcslt-search" value="" placeholder="'+ options.labels[0] +'" autocomplete="off" id="'+ uniqueId +'" />' +
'</li></ul>';
}
code += '<ul class="lc-select-dd-scroll">';
// cycle
opts_order.forEach((entry) => {
// single ungrouped option
if(entry.type === 'option') {
const group_key = entry.group,
opt_key = entry.value,
vals = structure.get(group_key).get(opt_key),
img = (vals.img) ? '<i class="lcslt-img" style="background-image: url(\''+ vals.img +'\')"></i>' : '',
sel_class = (vals.selected) ? 'lcslt-selected' : '',
dis_class = (vals.disabled || disabled_groups.indexOf(group_key) !== -1) ? 'lcslt-disabled': '',
hlight_class = (!highligh_set && sel_class) ? 'lcslt-dd-opt-hlight' : '';
// hide simple dropdown placeholder opt
if(!multiple_class && select.querySelector('option[value="'+ opt_key +'"]').hasAttribute('data-lcslt-placeh')) {
return;
}
code +=
'<li class="lcslt-dd-opt '+ sel_class +' '+ dis_class +' '+ hlight_class +'" data-val="'+ opt_key +'" role="button" tabindex="0">'+
'<span>'+ img + vals.name +'</span>'+
'</li>';
}
// whole optgroup block
if(entry.type === 'group') {
const group_key = entry.label,
dis_class = (disabled_groups.indexOf(group_key) !== -1) ? 'lcslt-disabled': '',
optgroup = select.querySelector('optgroup[label="'+ group_key +'"]'),
img = (optgroup && optgroup.hasAttribute('data-image') && optgroup.getAttribute('data-image')) ? '<i class="lcslt-img" style="background-image: url(\''+ optgroup.getAttribute('data-image').trim() +'\')"></i>' : '';
code +=
'<li class="lcslt-group '+ dis_class +'"><span class="lcslt-group-name">'+ img + group_key +'</span>' +
'<ul class="lcslt-group-opts">';
// group options
structure.get(group_key).forEach((opt, opt_key) => {
const vals = structure.get(group_key).get(opt_key),
img = (vals.img) ? '<i class="lcslt-img" style="background-image: url(\''+ vals.img +'\')"></i>' : '',
sel_class = (vals.selected) ? 'lcslt-selected' : '',
dis_class = (vals.disabled || disabled_groups.indexOf(group_key) !== -1) ? 'lcslt-disabled': '',
hlight_class = (!highligh_set && sel_class) ? 'lcslt-dd-opt-hlight' : '';
// hide simple dropdown placeholder opt
if(!multiple_class && select.querySelector('option[value="'+ opt_key +'"]').hasAttribute('data-lcslt-placeh')) {
return;
}
code +=
'<li class="lcslt-dd-opt '+ sel_class +' '+ dis_class +' '+ hlight_class +'" data-val="'+ opt_key +'" role="button" tabindex="0">'+
'<span>'+ img + vals.name +'</span>'+
'</li>';
});
code += '</ul></li>';
}
});
document.body.insertAdjacentHTML('beforeend', code +'</ul></div>');
document.querySelectorAll('.lcslt-dd-opt').forEach(opt => {
// option selection listener
opt.addEventListener("click", (e) => {
$this.clicked_dd_option(e, opt);
});
// option highlighter listener
opt.addEventListener("mouseenter", (e) => {
if(document.querySelector('.lcslt-dd-opt-hlight')) {
document.querySelector('.lcslt-dd-opt-hlight').classList.remove('lcslt-dd-opt-hlight');
}
if(!opt.classList.contains('lcslt-disabled')) {
opt.classList.add('lcslt-dd-opt-hlight');
}
});
opt.addEventListener("mouseleave", (e) => {
opt.classList.remove('lcslt-dd-opt-hlight');
});
});
// search listener
if(has_searchbar) {
// focus search field on open - on desktop
if(window.innerWidth > 1024 && options.autofocus_search) {
setTimeout(() => document.querySelector('input[name=lcslt-search]').focus(), 50);
}
if(document.querySelector('input[name=lcslt-search]')) {
document.querySelector('input[name=lcslt-search]').addEventListener("keyup", (e) => {
this.debounce('opts_search', 500, 'search_options');
});
}
}
// disable page scroll on element scroll
document.querySelector('.lc-select-dd-scroll').addEventListener('mouseenter', () => {
noscroll_window = [window.pageXOffset, window.pageYOffset];
});
document.querySelector('.lc-select-dd-scroll').addEventListener('mouseleave', () => {
noscroll_window = false;
});
};
/* actions on selection change */
this.on_val_change = function(trigger) {
const select = trigger.nextSibling,
values = Array.from( select.selectedOptions ).map(el=>el.value);
// trigger native "change" event
const event = new Event('change', {bubbles:true});
select.dispatchEvent(event);
// callback?
if(typeof(options.on_change) == 'function') {
options.on_change.call(this, values, select);
}
};
// HANDLERS
// deselect option clicking on .lcslt-multi-selected
this.deselect_option = function(e, trigger, opt) {
trigger.nextSibling.querySelector('option[value="'+ opt.getAttribute('data-val') +'"]').selected = false;
this.set_sel_content(trigger);
this.on_val_change(trigger);
};
// dropdown option click (enable / disable / ignore)
this.clicked_dd_option = function(e, opt) {
const is_multiple = active_trigger.classList.contains('lcslt-multiple'),
opt_val = opt.getAttribute('data-val'),
select = active_trigger.nextSibling;
// ignore if disabled or not multiple and already selected or not selected and max opts reached
if(
opt.classList.contains('lcslt-disabled') ||
(!is_multiple && opt.classList.contains('lcslt-selected')) ||
(!opt.classList.contains('lcslt-selected') && active_trigger.classList.contains('lcslt-max-opts'))
) {
return false;
}
// if not multiple - unselect other options
if(!is_multiple) {
document.querySelectorAll('.lcslt-dd-opt').forEach(dd_opt => {
if( dd_opt.getAttribute('data-val') != opt_val ) {
dd_opt.classList.remove('lcslt-selected');
}
});
select.querySelectorAll('option').forEach(select_opt => {
if( select_opt.getAttribute('value') != opt_val ) {
select_opt.selected = false;
}
});
}
// toggle selection
opt.classList.toggle('lcslt-selected');
opt.classList.remove('lcslt-dd-opt-hlight');
select.querySelector('option[value="'+ opt_val +'"]').selected = !select.querySelector('option[value="'+ opt_val +'"]').selected;
// sync with trigger
this.set_sel_content();
// spread events
this.on_val_change(active_trigger);
// be sure position is right
if(is_multiple) {
this.set_dd_position();
}
// simple dropdown - close it after choice
else if(active_trigger) {
active_trigger.click();
}
};
// options search
this.search_options = function() {
if(!document.querySelector('input[name=lcslt-search]')) {
return false;
}
const val = document.querySelector('input[name=lcslt-search]').value.trim(),
groups = document.querySelectorAll('.lcslt-group-name'),
opts = document.querySelectorAll('.lcslt-dd-opt'),
no_results_li = document.querySelector('.lcslt-no-results');
if(val.length < 2) {
document.getElementById('lc-select-dd').classList.remove('lcslt-is-searching');
groups.forEach(group => {
group.style.removeProperty('display');
});
opts.forEach(opt => {
opt.style.removeProperty('display');
});
if(no_results_li) {
no_results_li.remove();
}
}
else {
document.getElementById('lc-select-dd').classList.add('lcslt-is-searching');
groups.forEach(group => {
group.style.display = 'none';
});
// cycle
const val_arr = val.split(' ');
let no_results = true;
opts.forEach(opt => {
let matching = false;
val_arr.some((val_part) => {
if( opt.querySelector('span').innerHTML.toLowerCase().indexOf( val_part.toLowerCase() ) !== -1 ) {
matching = true;
no_results = false;
}
});
(matching) ? opt.style.removeProperty('display') : opt.style.display = 'none';
});
// append "no results" element?
if(no_results) {
if(!no_results_li) {
document.querySelector('.lc-select-dd-scroll').insertAdjacentHTML('beforeend', '<li class="lcslt-no-results"><span>'+ options.labels[3] +'</span></li>');
}
} else {
if(no_results_li) {
no_results_li.remove();
}
}
}
};
/*
* UTILITY FUNCTION - debounce action to run once after X time
*
* @param (string) action_name
* @param (int) timing - milliseconds to debounce
* @param (string) - class method name to call after debouncing
* @param (mixed) - extra parameters to pass to callback function
*/
this.debounce = function(action_name, timing, cb_function, cb_params) {
if( typeof(debounced_vars[ action_name ]) != 'undefined' && debounced_vars[ action_name ]) {
clearTimeout(debounced_vars[ action_name ]);
}
const $this = this;
debounced_vars[ action_name ] = setTimeout(() => {
$this[cb_function].call($this, cb_params);
}, timing);
};
/* CSS - creates inline CSS into the page */
this.generate_style = function() {
const magnifier_svg = " url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/PjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiB3aWR0aD0iNTg3LjQ3MXB4IiBoZWlnaHQ9IjU4Ny40NzFweCIgdmlld0JveD0iMCAwIDU4Ny40NzEgNTg3LjQ3MSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNTg3LjQ3MSA1ODcuNDcxOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PGc+PGc+PHBhdGggZD0iTTIyMC4zMDIsNDQwLjYwNGMxMjEuNDc2LDAsMjIwLjMwMi05OC44MjYsMjIwLjMwMi0yMjAuMzAyQzQ0MC42MDQsOTguODI2LDM0MS43NzcsMCwyMjAuMzAyLDBDOTguODI2LDAsMCw5OC44MjYsMCwyMjAuMzAyQzAsMzQxLjc3Nyw5OC44MjYsNDQwLjYwNCwyMjAuMzAyLDQ0MC42MDR6IE0yMjAuMzAyLDcxLjE0MmM4Mi4yNDcsMCwxNDkuMTU5LDY2LjkxMywxNDkuMTU5LDE0OS4xNTljMCw4Mi4yNDgtNjYuOTEyLDE0OS4xNi0xNDkuMTU5LDE0OS4xNnMtMTQ5LjE2LTY2LjkxMi0xNDkuMTYtMTQ5LjE2QzcxLjE0MiwxMzguMDU1LDEzOC4wNTUsNzEuMTQyLDIyMC4zMDIsNzEuMTQyeiIvPjxwYXRoIGQ9Ik01MjUuNTIzLDU4Ny40NzFjMTYuNTU1LDAsMzIuMTEzLTYuNDQ3LDQzLjgwMS0xOC4xNThjMTEuNjk5LTExLjY4LDE4LjE0Ni0yNy4yMzQsMTguMTQ2LTQzLjc5MWMwLTE2LjU1My02LjQ0Ny0zMi4xMTUtMTguMTUyLTQzLjgyMkw0NDYuNjQzLDM1OS4wMjNjLTMuMjYyLTMuMjYyLTcuNDc1LTUuMDYxLTExLjg1OS01LjA2MWMtNS40NDksMC0xMC40NjUsMi43MTEtMTMuNzYyLDcuNDM4Yy0xNi4yMzgsMjMuMzE4LTM2LjI5Nyw0My4zNzctNTkuNjEzLDU5LjYxNWMtNC4yNTgsMi45NjUtNi45NDcsNy40NjctNy4zNzksMTIuMzUyYy0wLjQyOCw0LjgyOCwxLjM5Myw5LjY2Niw0Ljk5OCwxMy4yN2wxMjIuNjc0LDEyMi42NzZDNDkzLjQwNiw1ODEuMDIzLDUwOC45NjksNTg3LjQ3MSw1MjUuNTIzLDU4Ny40NzF6Ii8+PC9nPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48L3N2Zz4=')";
document.head.insertAdjacentHTML('beforeend',
`<style>
.lcslt-displaynone {
display: none !important;
}
.lcslt-wrap {
position: relative;
display: inline-block;
}
.lcslt-wrap select {
display: none !important;
}
.lcslt {
display: flex;
align-items: center;
flex-direction: row;
flex-wrap: wrap;
width: 100%;
min-height: 15px;
padding: 5px 30px 5px 5px;
position: relative;
overflow: hidden;
font-size: 1rem;
}
.lcslt:not(.lcslt-disabled):not(.lcslt-max-opts) {
cursor: pointer;
}
.lcslt:not(.lcslt-multiple):after {
content: "";
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 6px solid #444;
display: inline-block;
position: absolute;
right: 6px;
transition: transform .3s ease;
}
.lcslt.lcslt_dd-open:after {
transform: rotate(180deg);
}
.lcslt:not(.lcslt-multiple) > span {
line-height: normal;
}
.lcslt span,
.lcslt-multi-selected {
max-width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.lcslt-multiple {
padding: 5px;
height: auto;
line-height: 0;
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 5px;
align-items: center;
justify-content: flex-start;
}
.lcslt span:not(.lcslt-placeholder):not(.lcslt-multi-callout) {
line-height: 1.1em;
font-size: 0.95em;
}
.lcslt-opt {
display: inline-block;
margin: 0 0 5px 5px;
}