-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
datalist-polyfill.js
705 lines (596 loc) · 25.3 KB
/
datalist-polyfill.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
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
/*
* Datalist polyfill - https://github.com/mfranzke/datalist-polyfill
* @license Copyright(c) 2017 by Maximilian Franzke
* Supported by Christian, Johannes, @mitchhentges, @mertenhanisch, @ailintom, @Kravimir, @mischah, @hryamzik, @ottoville, @IceCreamYou, @wlekin, @eddr, @beebee1987, @mricherzhagen, @acespace90, @damien-git, @nexces, @Sora2455, @jscho13, @alexirion and @vinyfc93 - many thanks for that !
*/
/*
* A minimal and dependency-free vanilla JavaScript datalist polyfill.
* Supports all standard's functionality as well as mimics other browsers behavior.
* Tests for native support of an inputs elements datalist functionality.
* Elsewhere the functionality gets emulated by a select element.
*/
(function () {
'use strict';
// Performance: Set local variables
var dcmnt = window.document,
ua = window.navigator.userAgent,
// Feature detection
datalistSupported =
'list' in dcmnt.createElement('input') &&
Boolean(dcmnt.createElement('datalist') && window.HTMLDataListElement),
// IE & EDGE browser detection via UserAgent
// TODO: obviously ugly. But sadly necessary until Microsoft enhances the UX within EDGE (compare to https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9573654/)
// Tested against the following UA strings: http://useragentstring.com/pages/useragentstring.php?name=Internet+Explorer
// And adapted out of https://gist.github.com/gaboratorium/25f08b76eb82b1e7b91b01a0448f8b1d :
isGteIE10 = Boolean(/MSIE\s1[01]./.test(ua) || /rv:11./.test(ua)),
isEDGE = Boolean(ua.indexOf('Edge/') !== -1);
// Let's break here, if it's even already supported ... and not IE10+ or EDGE
if (datalistSupported && !isGteIE10 && !isEDGE) {
return false;
}
// .matches polyfill
// TODO: probably needs enhancement on the expected to be supported browsers
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector;
}
// Define some global settings and configurations
var touched = false,
// Speaking variables for the different keycodes
keyENTER = 13,
keyESC = 27,
keyUP = 38,
keyDOWN = 40,
// Defining the text / value seperator for displaying the value and text values ...
textValueSeperator = ' / ',
// ... and defining the different input types that are supported by this polyfill
supportedTypes = ['text', 'email', 'number', 'search', 'tel', 'url'],
// Classes for elements
classNameInput = 'polyfilled',
classNamePolyfillingSelect = '.polyfilling',
// Defining a most likely unique polyfill string
uniquePolyfillString = '###[P0LYFlLLed]###';
// Differentiate for touch interactions, adapted by https://medium.com/@david.gilbertson/the-only-way-to-detect-touch-with-javascript-7791a3346685
window.addEventListener('touchstart', function onFirstTouch() {
touched = true;
window.removeEventListener('touchstart', onFirstTouch);
});
// For observing any changes to the option elements within the datalist elements, define MutationObserver initially
var MutationObserver =
window.MutationObserver || window.WebKitMutationObserver,
obs;
// Define a new observer
if (typeof MutationObserver !== 'undefined') {
obs = new MutationObserver(function (mutations) {
var datalistNeedsAnUpdate = false;
// Look through all mutations that just occured
mutations.forEach(function (mutation) {
// Check if any of the mutated nodes was a datalist
if (
mutation.target instanceof HTMLElement &&
mutation.target.tagName.toLowerCase() === 'datalist' &&
mutation.addedNodes.length > 1
) {
datalistNeedsAnUpdate = mutation.target;
}
});
if (datalistNeedsAnUpdate) {
var input = dcmnt.querySelector(
// eslint-disable-next-line prettier/prettier
'input[list="' + datalistNeedsAnUpdate.id + '"]'
);
if (getInputValue(input) !== '') {
// Prepare the options and toggle the visiblity afterwards
toggleVisibility(
prepOptions(datalistNeedsAnUpdate, input).length,
// eslint-disable-next-line prettier/prettier
datalistNeedsAnUpdate.querySelector(classNamePolyfillingSelect)
);
}
}
});
}
// Function regarding the inputs interactions on keyup event
var inputInputList = function (event) {
var input = event.target,
datalist = input.list,
keyOpen = event.keyCode === keyUP || event.keyCode === keyDOWN;
// Check for whether the events target was an input and still check for an existing instance of the datalist and polyfilling select
if (input.tagName.toLowerCase() !== 'input' || datalist === null) {
return;
}
// Handling IE10+ & EDGE
if (isGteIE10 || isEDGE) {
// On keypress check for value
if (
getInputValue(input) !== '' &&
!keyOpen &&
event.keyCode !== keyENTER &&
event.keyCode !== keyESC &&
// As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here
(isGteIE10 || input.type === 'text')
) {
updateIEOptions(input, datalist);
// TODO: Check whether this update is necessary depending on the options values
input.focus();
}
return;
}
var visible = false,
// Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted)
datalistSelect =
datalist.querySelector(classNamePolyfillingSelect) ||
setUpPolyfillingSelect(input, datalist);
// On an ESC or ENTER key press within the input, let's break here and afterwards hide the datalist select, but if the input contains a value or one of the opening keys have been pressed ...
if (
event.keyCode !== keyESC &&
event.keyCode !== keyENTER &&
(getInputValue(input) !== '' || keyOpen) &&
datalistSelect !== undefined
) {
// ... prepare the options
if (prepOptions(datalist, input).length > 0) {
visible = true;
}
var firstEntry = 0,
lastEntry = datalistSelect.options.length - 1;
// ... preselect best fitting index
if (touched) {
datalistSelect.selectedIndex = firstEntry;
} else if (keyOpen && input.getAttribute('type') !== 'number') {
datalistSelect.selectedIndex =
event.keyCode === keyUP ? lastEntry : firstEntry;
// ... and on arrow up or down keys, focus the select
datalistSelect.focus();
}
}
// Toggle the visibility of the datalist select according to previous checks
toggleVisibility(visible, datalistSelect);
};
// On keypress check all options for that as a substring, save the original value as a data-attribute and preset that inputs value (for sorting) for all option values (probably as well enhanced by a token)
var updateIEOptions = function (input, datalist) {
var inputValue = getInputValue(input);
// Loop through the options
Array.prototype.slice.call(datalist.options, 0).forEach(function (option) {
// We're using .getAttribute instead of .dataset here for IE10-
var dataOriginalvalue = option.getAttribute('data-originalvalue'),
originalValue = dataOriginalvalue || option.value;
// In case of that the original value hasn't been saved as data so far, do that now
if (!dataOriginalvalue) {
// We're using .setAttribute instead of .dataset here for IE10-
option.setAttribute('data-originalvalue', originalValue);
}
// As we'd manipulate the value in the next step, we'd like to put in that value as either a label or text if none of those exist
if (!option.label && !option.text) {
option.label = originalValue;
}
/* As mentioned in the discussion within #GH-63:
Check for whether the current option is a valid suggestion and replace its value by
- the current input string, as IE10+ and EDGE don't do substring, but only prefix matching (#GH-36, #GH-39)
- followed by a unique string that should prevent any interferance
- and the original string, that is still necessary e.g. for sorting within the suggestions list
As the value is being inserted on users selection, we'll replace that one within the upfollowing inputInputListIE function
*/
option.value = isValidSuggestion(option, inputValue)
? inputValue + uniquePolyfillString + originalValue.toLowerCase()
: originalValue;
});
};
// Check for the input and probably replace by correct options elements value
var inputInputListIE = function (event) {
var input = event.target,
datalist = input.list;
if (
!input.matches('input[list]') ||
!input.matches('.' + classNameInput) ||
!datalist
) {
return;
}
// Query for related option - and escaping the value as doublequotes wouldn't work
var option = datalist.querySelector(
'option[value="' +
getInputValue(input).replace(/\\([\s\S])|(")/g, '\\$1$2') +
// eslint-disable-next-line prettier/prettier
'"]'
);
// We're using .getAttribute instead of .dataset here for IE10-
if (option && option.getAttribute('data-originalvalue')) {
setInputValue(input, option.getAttribute('data-originalvalue'));
}
};
// Check for whether this is a valid suggestion
var isValidSuggestion = function (option, inputValue) {
var optValue = option.value.toLowerCase(),
inptValue = inputValue.toLowerCase(),
label = option.getAttribute('label'),
text = option.text.toLowerCase();
/*
"Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn't the empty string, represents a suggestion. Each suggestion has a value and a label."
"If appropriate, the user agent should use the suggestion's label and value to identify the suggestion to the user."
*/
return Boolean(
option.disabled === false &&
((optValue !== '' && optValue.indexOf(inptValue) !== -1) ||
(label && label.toLowerCase().indexOf(inptValue) !== -1) ||
// eslint-disable-next-line prettier/prettier
(text !== '' && text.indexOf(inptValue) !== -1))
);
};
// Focusin and -out events
var changesInputList = function (event) {
// Check for correct element on this event delegation
if (!event.target.matches('input[list]')) {
return;
}
var input = event.target,
datalist = input.list;
// Check for whether the events target was an input and still check for an existing instance of the datalist
if (input.tagName.toLowerCase() !== 'input' || datalist === null) {
return;
}
// Test for whether this input has already been enhanced by the polyfill
if (!input.matches('.' + classNameInput)) {
prepareInput(input, event.type);
}
// #GH-49: Microsoft EDGE / datalist popups get "emptied" when receiving focus via tabbing
if (isEDGE && event.type === 'focusin') {
// Set the value of the first option to it's value - this actually triggers a redraw of the complete list
var firstOption = input.list.options[0];
// eslint-disable-next-line no-self-assign
firstOption.value = firstOption.value;
}
// Break here for IE10+ & EDGE
if (isGteIE10 || isEDGE) {
return;
}
var // Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted)
datalistSelect =
datalist.querySelector(classNamePolyfillingSelect) ||
setUpPolyfillingSelect(input, datalist),
// Either have the select set to the state to get displayed in case of that it would have been focused or because it's the target on the inputs blur - and check for general existance of any option as suggestions
visible =
datalistSelect &&
datalistSelect.querySelector('option:not(:disabled)') &&
((event.type === 'focusin' && getInputValue(input) !== '') ||
(event.relatedTarget && event.relatedTarget === datalistSelect));
// Toggle the visibility of the datalist select according to previous checks
toggleVisibility(visible, datalistSelect);
};
// Prepare the input
var prepareInput = function (input, eventType) {
// We'd like to prevent autocomplete on the input datalist field
input.setAttribute('autocomplete', 'off');
// WAI ARIA attributes
input.setAttribute('role', 'textbox');
input.setAttribute('aria-haspopup', 'true');
input.setAttribute('aria-autocomplete', 'list');
input.setAttribute('aria-owns', input.getAttribute('list'));
// Bind the keyup event on the related datalists input
if (eventType === 'focusin') {
input.addEventListener('keyup', inputInputList);
input.addEventListener('focusout', changesInputList, true);
// As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here
if (isGteIE10 || (isEDGE && input.type === 'text')) {
input.addEventListener('input', inputInputListIE);
}
} else if (eventType === 'blur') {
input.removeEventListener('keyup', inputInputList);
input.removeEventListener('focusout', changesInputList, true);
// As only EDGE doesn't trigger the input event after selecting an item via mouse, we need to differentiate here
if (isGteIE10 || (isEDGE && input.type === 'text')) {
input.removeEventListener('input', inputInputListIE);
}
}
// Add class for identifying that this input is even already being polyfilled
input.className += ' ' + classNameInput;
};
// Get the input value for dividing regular and mail types
var getInputValue = function (input) {
// In case of type=email and multiple attribute, we would need to grab the last piece
// Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly
return input.getAttribute('type') === 'email' &&
input.getAttribute('multiple') !== null
? input.value.slice(Math.max(0, input.value.lastIndexOf(',') + 1))
: input.value;
};
// Set the input value for dividing regular and mail types
var setInputValue = function (input, datalistSelectValue) {
var lastSeperator;
// In case of type=email and multiple attribute, we need to set up the resulting inputs value differently
input.value =
// Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly
input.getAttribute('type') === 'email' &&
input.getAttribute('multiple') !== null &&
(lastSeperator = input.value.lastIndexOf(',')) > -1
? input.value.slice(0, lastSeperator) + ',' + datalistSelectValue
: datalistSelectValue;
};
// Binding the focus event - matching the input[list]s happens in the function afterwards
dcmnt.addEventListener('focusin', changesInputList, true);
// Break here for IE10+ & EDGE
if (isGteIE10 || isEDGE) {
return;
}
// Function for preparing and sorting the options/suggestions
var prepOptions = function (datalist, input) {
if (typeof obs !== 'undefined') {
obs.disconnect();
}
var // Creating the select if there's no instance so far (e.g. because of that it hasn't been handled or it has been dynamically inserted)
datalistSelect =
datalist.querySelector(classNamePolyfillingSelect) ||
setUpPolyfillingSelect(input, datalist),
inputValue = getInputValue(input),
newSelectValues = dcmnt.createDocumentFragment(),
disabledValues = dcmnt.createDocumentFragment();
// Create an array out of the options list
Array.prototype.slice
.call(datalist.querySelectorAll('option:not(:disabled)'))
// ... sort all entries and
.sort(function (a, b) {
var aValue = a.value,
bValue = b.value;
// Using the knowledge that the values are URLs to allow the user to omit the scheme part and perform intelligent matching on the domain name
if (input.getAttribute('type') === 'url') {
aValue = aValue.replace(/(^\w+:|^)\/\//, '');
bValue = bValue.replace(/(^\w+:|^)\/\//, '');
}
return aValue.localeCompare(bValue);
})
.forEach(function (opt) {
var optionValue = opt.value,
label = opt.getAttribute('label'),
text = opt.text;
// Put this option into the fragment that is meant to get inserted into the select. Additionally according to the specs ...
// TODO: This might get slightly changed/optimized in a future release
if (isValidSuggestion(opt, inputValue)) {
var textOptionPart = text.slice(
0,
// eslint-disable-next-line prettier/prettier
optionValue.length + textValueSeperator.length
),
optionPart = optionValue + textValueSeperator;
// The innertext should be 'value seperator text' in case they are different
if (
text &&
!label &&
text !== optionValue &&
textOptionPart !== optionPart
) {
opt.textContent = optionValue + textValueSeperator + text;
} else if (!opt.text) {
// Manipulating the option inner text, that would get displayed
opt.textContent = label || optionValue;
}
newSelectValues.appendChild(opt);
} else {
// ... or put this option that isn't relevant to the users into the fragment that is supposed to get inserted outside of the select
disabledValues.appendChild(opt);
}
});
// Input the options fragment into the datalists select
datalistSelect.appendChild(newSelectValues);
var datalistSelectOptionsLength = datalistSelect.options.length;
datalistSelect.size =
datalistSelectOptionsLength > 10 ? 10 : datalistSelectOptionsLength;
datalistSelect.multiple = !touched && datalistSelectOptionsLength < 2;
// Input the unused options as siblings next to the select - and differentiate in between the regular, and the IE9 fix syntax upfront
(datalist.querySelectorAll('.ie9_fix')[0] || datalist).appendChild(
// eslint-disable-next-line prettier/prettier
disabledValues
);
if (typeof obs !== 'undefined') {
obs.observe(datalist, {
childList: true,
});
}
return datalistSelect.options;
};
// Define function for setting up the polyfilling select
var setUpPolyfillingSelect = function (input, datalist) {
// Check for whether it's of one of the supported input types defined at the beginning
// Using .getAttribute here for IE9 purpose - elsewhere it wouldn't return the newer HTML5 values correctly
// and still check for an existing instance
if (
(input.getAttribute('type') &&
supportedTypes.indexOf(input.getAttribute('type')) === -1) ||
datalist === null
) {
return;
}
var rects = input.getClientRects(),
// Measurements
inputStyles = window.getComputedStyle(input),
datalistSelect = dcmnt.createElement('select');
// Setting a class for easier identifying that select afterwards
datalistSelect.setAttribute('class', classNamePolyfillingSelect.slice(1));
// Set general styling related definitions
datalistSelect.style.position = 'absolute';
// Initially hiding the datalist select
toggleVisibility(false, datalistSelect);
// The select itself shouldn't be a possible target for tabbing
datalistSelect.setAttribute('tabindex', '-1');
// WAI ARIA attributes
datalistSelect.setAttribute('aria-live', 'polite');
datalistSelect.setAttribute('role', 'listbox');
if (!touched) {
datalistSelect.setAttribute('aria-multiselectable', 'false');
}
// The select should get positioned underneath the input field ...
if (inputStyles.getPropertyValue('display') === 'block') {
datalistSelect.style.marginTop =
'-' + inputStyles.getPropertyValue('margin-bottom');
} else {
var direction =
inputStyles.getPropertyValue('direction') === 'rtl' ? 'right' : 'left';
datalistSelect.style.setProperty(
'margin-' + direction,
'-' +
(rects[0].width +
parseFloat(inputStyles.getPropertyValue('margin-' + direction))) +
// eslint-disable-next-line prettier/prettier
'px'
);
datalistSelect.style.marginTop =
parseInt(rects[0].height + (input.offsetTop - datalist.offsetTop), 10) +
'px';
}
// Set the polyfilling selects border-radius equally to the one by the polyfilled input
datalistSelect.style.borderRadius =
inputStyles.getPropertyValue('border-radius');
datalistSelect.style.minWidth = rects[0].width + 'px';
if (touched) {
var messageElement = dcmnt.createElement('option');
// ... and it's first entry should contain the localized message to select an entry
messageElement.textContent = datalist.title;
// ... and disable this option, as it shouldn't get selected by the user
messageElement.disabled = true;
// ... and assign a dividable class to it
messageElement.setAttribute('class', 'message');
// ... and finally insert it into the select
datalistSelect.appendChild(messageElement);
}
// Add select to datalist element ...
datalist.appendChild(datalistSelect);
// ... and our upfollowing functions to the related event
if (touched) {
datalistSelect.addEventListener('change', changeDataListSelect);
} else {
datalistSelect.addEventListener('click', changeDataListSelect);
}
datalistSelect.addEventListener('blur', changeDataListSelect);
datalistSelect.addEventListener('keydown', changeDataListSelect);
datalistSelect.addEventListener('keypress', datalistSelectKeyPress);
return datalistSelect;
};
// Functions regarding changes to the datalist polyfilling created selects keypress
var datalistSelectKeyPress = function (event) {
var datalistSelect = event.target,
datalist = datalistSelect.parentNode,
input = dcmnt.querySelector('input[list="' + datalist.id + '"]');
// Check for whether the events target was a select or whether the input doesn't exist
if (datalistSelect.tagName.toLowerCase() !== 'select' || input === null) {
return;
}
// Determine a relevant key - either printable characters (that would have a length of 1) or controlling like Backspace
if (event.key && (event.key === 'Backspace' || event.key.length === 1)) {
input.focus();
if (event.key === 'Backspace') {
input.value = input.value.slice(0, -1);
// Dispatch the input event on the related input[list]
dispatchInputEvent(input);
} else {
input.value += event.key;
}
prepOptions(datalist, input);
}
};
// Change, Click, Blur, Keydown
var changeDataListSelect = function (event) {
var datalistSelect = event.currentTarget,
datalist = datalistSelect.parentNode,
input = dcmnt.querySelector('input[list="' + datalist.id + '"]');
// Check for whether the events target was a select or whether the input doesn't exist
if (datalistSelect.tagName.toLowerCase() !== 'select' || input === null) {
return;
}
var eventType = event.type,
// ENTER and ESC
visible =
eventType === 'keydown' &&
event.keyCode !== keyENTER &&
event.keyCode !== keyESC;
// On change, click or after pressing ENTER or TAB key, input the selects value into the input on a change within the list
if (
(eventType === 'change' ||
eventType === 'click' ||
(eventType === 'keydown' &&
(event.keyCode === keyENTER || event.key === 'Tab'))) &&
datalistSelect.value.length > 0 &&
datalistSelect.value !== datalist.title
) {
setInputValue(input, datalistSelect.value);
// Dispatch the input event on the related input[list]
dispatchInputEvent(input);
// Finally focusing the input, as other browser do this as well
if (event.key !== 'Tab') {
input.focus();
}
// #GH-51 / Prevent the form to be submitted on selecting a value via ENTER key within the select
if (event.keyCode === keyENTER) {
event.preventDefault();
}
// Set the visibility to false afterwards, as we're done here
visible = false;
} else if (eventType === 'keydown' && event.keyCode === keyESC) {
// In case of the ESC key being pressed, we still want to focus the input[list]
input.focus();
}
// Toggle the visibility of the datalist select according to previous checks
toggleVisibility(visible, datalistSelect);
};
// Create and dispatch the input event; divided for IE9 usage
var dispatchInputEvent = function (input) {
var evt;
if (typeof Event === 'function') {
evt = new Event('input', {
bubbles: true,
});
} else {
evt = dcmnt.createEvent('Event');
evt.initEvent('input', true, false);
}
input.dispatchEvent(evt);
};
// Toggle the visibility of the datalist select
var toggleVisibility = function (visible, datalistSelect) {
if (visible) {
datalistSelect.removeAttribute('hidden');
} else {
datalistSelect.setAttributeNode(dcmnt.createAttribute('hidden'));
}
datalistSelect.setAttribute('aria-hidden', (!visible).toString());
};
// Emulate the two properties regarding the datalist and input elements
// list property / https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement
(function (constructor) {
if (
constructor &&
constructor.prototype &&
constructor.prototype.list === undefined
) {
Object.defineProperty(constructor.prototype, 'list', {
get: function () {
/*
According to the specs ...
"The list IDL attribute must return the current suggestions source element, if any, or null otherwise."
"If there is no list attribute, or if there is no element with that ID, or if the first element with that ID is not a datalist element, then there is no suggestions source element."
*/
var element = dcmnt.querySelector('#' + this.getAttribute('list'));
return typeof this === 'object' &&
this instanceof constructor &&
element &&
element.matches('datalist')
? element
: null;
},
});
}
})(window.HTMLInputElement);
// Options property / https://developer.mozilla.org/en/docs/Web/API/HTMLDataListElement
(function (constructor) {
if (
constructor &&
constructor.prototype &&
constructor.prototype.options === undefined
) {
Object.defineProperty(constructor.prototype, 'options', {
get: function () {
return typeof this === 'object' && this instanceof constructor
? this.querySelectorAll('option')
: null;
},
});
}
})(window.HTMLElement);
})();