forked from mfranzke/datalist-polyfill
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datalist-polyfill.js
392 lines (311 loc) · 15.8 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
/*
* datalist-polyfill.js - https://github.com/mfranzke/datalist-polyfill
* @license Copyright(c) 2017 by Maximilian Franzke
* Supported by Christian, Johannes, @ailintom, @Kravimir, Michael and @hryamzik - many thanks for that !
*//*
* A lightweight and library dependency free vanilla JavaScript datalist polyfill.
* Tests for native support of an inputs elements datalist functionality.
* Elsewhere the functionality gets emulated by a select element.
*/
( function() {
'use strict';
// feature detection
var nativedatalist = !!( 'list' in document.createElement( 'input' ) ) &&
!!( document.createElement( 'datalist' ) && window.HTMLDataListElement );
// in case of that the feature doesn't exist, emulate it's functionality
if ( !nativedatalist ) {
// 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() {
if ( typeof( this ) === 'object' && this instanceof constructor ) {
var list = this.getAttribute( 'list' );
return document.getElementById( list );
}
return 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() {
if ( typeof( this ) === 'object' && this instanceof constructor ) {
return this.getElementsByTagName( 'option' );
}
}
});
}
})( window.HTMLElement );
// identify whether a select multiple is feasible
var touched = false,
// introduced speaking variables for the different keycodes
keyENTER = 13,
keyESC = 27,
keyUP = 38,
keyDOWN = 40,
// and defining the different input types that are supported by this polyfill
supportedTypes = [ 'text', 'email', 'number', 'search', 'tel', 'url' ];
// 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 );
});
// function regarding the inputs interactions
var inputInputList = function( event ) {
var $eventTarget = event.target,
eventTargetTagName = $eventTarget.tagName.toLowerCase();
// check for whether the events target was an input datalist
if ( eventTargetTagName && eventTargetTagName === 'input' && $eventTarget.getAttribute( 'list' ) ) {
var list = $eventTarget.getAttribute( 'list' ),
$dataList = document.getElementById( list );
// still check for an existing instance
if ( $dataList !== null ) {
var $dataListSelect = $dataList.getElementsByClassName( 'polyfilling' )[0];
// still check for an existing instance
if ( $dataListSelect !== undefined ) {
// on an ESC key press within the input, let's break here and hide the select
if ( event.keyCode === keyESC ) {
$dataListSelect.setAttributeNode( document.createAttribute( 'hidden' ) );
$dataListSelect.setAttribute( 'aria-hidden', 'true' );
return;
}
var $dataListOptions = $dataList.querySelectorAll( 'option:not([disabled]):not(.message)' ),
inputValue = $eventTarget.value,
newSelectValues = document.createDocumentFragment(),
disabledValues = document.createDocumentFragment(),
visible = false,
multipleEmails = ( $eventTarget.type === 'email' && $eventTarget.multiple ),
keyOpen = ( event.keyCode === keyUP || event.keyCode === keyDOWN );
// in case of type=email and multiple attribute, we would need to split the inputs value into pieces
if ( multipleEmails ) {
var multipleEntries = inputValue.split( ',' ),
relevantIndex = multipleEntries.length - 1;
inputValue = multipleEntries[ relevantIndex ].trim();
}
// if the input contains a value, than ...
if ( inputValue !== '' || keyOpen ) {
// ... create an array out of the options list
var nodeArray = Array.prototype.slice.call( $dataListOptions );
// ... sort all entries and
nodeArray.sort( function( a, b ) {
return a.value.localeCompare( b.value );
}).forEach( function( opt ) {
var optionValue = opt.value;
// ... put this option into the fragment that is meant to get inserted into the select
// "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." (W3C)
if ( optionValue !== '' && optionValue.toLowerCase().indexOf( inputValue.toLowerCase() ) !== -1 && opt.disabled === false ) {
var label = opt.label,
labelValueSeperator = ' / ',
labelOptionPart = label.substr( 0, optionValue.length + labelValueSeperator.length ),
optionPart = optionValue + labelValueSeperator;
// the innertext should be value / label in case of that they are different
if ( label && label !== optionValue && labelOptionPart !== optionPart ) {
opt.innerText = optionValue + labelValueSeperator + label;
// remove the label attribute, as it's being displayed differently on desktop and iOS Safari for our construct
opt.setAttribute( 'data-label', opt.getAttribute( 'label' ) );
opt.removeAttribute( 'label' );
} else // manipulating the option inner text, that would get displayed
if ( !opt.innerText.trim() ) {
opt.innerText = optionValue;
}
newSelectValues.appendChild( opt );
// ... and set the state of the select to get displayed in that case
visible = true;
} 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,
firstEntry = 0,
lastEntry = dataListSelectOptionsLength - 1;
$dataListSelect.size = ( dataListSelectOptionsLength > 10 ) ? 10 : dataListSelectOptionsLength;
$dataListSelect.multiple = ( !touched && dataListSelectOptionsLength < 2 );
if ( touched ) {
// preselect best fitting index
$dataListSelect.selectedIndex = firstEntry;
} else if ( $dataListSelect.selectedIndex === -1 ) {
switch( event.keyCode ) {
case keyUP:
$dataListSelect.selectedIndex = lastEntry;
break;
case keyDOWN:
$dataListSelect.selectedIndex = firstEntry;
break;
}
}
// input the unused options as siblings next to the select - and differentiate in between the regular, and the IE9 fix syntax upfront
var $dataListAppend = $dataList.getElementsByClassName( 'ie9_fix' )[0] || $dataList;
$dataListAppend.appendChild( disabledValues );
}
// toggle the visibility of the select according to previous checks
if ( visible ) {
$dataListSelect.removeAttribute( 'hidden' );
} else {
$dataListSelect.setAttributeNode( document.createAttribute( 'hidden' ) );
}
$dataListSelect.setAttribute( 'aria-hidden', ( !visible ).toString() );
// on arrow up or down keys, focus the select
if ( keyOpen ) {
$dataListSelect.focus();
}
}
}
}
};
// focus or blur events
var changesInputList = function( event ) {
var $eventTarget = event.target,
eventTargetTagName = $eventTarget.tagName.toLowerCase(),
inputType = $eventTarget.type,
inputStyles = window.getComputedStyle( $eventTarget );
// check for whether the events target was an input datalist and whether it's of one of the supported input types defined above
if ( eventTargetTagName && eventTargetTagName === 'input' && $eventTarget.getAttribute( 'list' ) && supportedTypes.indexOf( inputType ) > -1 ) {
var eventType = event.type,
list = $eventTarget.getAttribute( 'list' ),
$dataList = document.getElementById( list );
// still check for an existing instance
if ( $dataList !== null ) {
var $dataListSelect = $dataList.getElementsByClassName( 'polyfilling' )[0],
// 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
visible = ( ( eventType === 'focus' && event.target.value !== '' ) || ( event.relatedTarget && event.relatedTarget === $dataListSelect ) ),
message = $dataList.title;
// 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)
if ( $dataListSelect === undefined ) {
var rects = $eventTarget.getClientRects(),
// measurements
inputStyleMarginRight = parseFloat( inputStyles.getPropertyValue( 'margin-right' ) ),
inputStyleMarginLeft = parseFloat( inputStyles.getPropertyValue( 'margin-left' ) );
$dataListSelect = document.createElement( 'select' );
// setting a class for easier selecting that select afterwards
$dataListSelect.setAttribute( 'class', 'polyfilling' );
// set general styling related definitions
$dataListSelect.setAttributeNode( document.createAttribute( 'hidden' ) );
$dataListSelect.style.position = 'absolute';
// WAI ARIA attributes
$dataListSelect.setAttribute( 'aria-hidden', 'true' );
$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 {
if ( inputStyles.getPropertyValue( 'direction' ) === 'rtl' ) {
$dataListSelect.style.marginRight = '-' + ( rects[0].width + inputStyleMarginLeft ) + 'px';
} else {
$dataListSelect.style.marginLeft = '-' + ( rects[0].width + inputStyleMarginRight ) + 'px';
}
$dataListSelect.style.marginTop = rects[0].height + 'px';
}
// set the polyfilling selects border-radius equally as the one by the polyfilled input
$dataListSelect.style.borderRadius = inputStyles.getPropertyValue( 'border-radius' );
$dataListSelect.style.minWidth = rects[0].width + 'px';
if ( touched ) {
var $message = document.createElement( 'option' );
// ... and it's first entry should contain the localized message to select an entry
$message.innerText = message;
// ... and disable this option, as it shouldn't get selected by the user
$message.disabled = true;
// ... and assign a dividable class to it
$message.setAttribute( 'class', 'message' );
// ... and finally insert it into the select
$dataListSelect.appendChild( $message );
}
// add select to datalist element ...
$dataList.appendChild( $dataListSelect );
// ... and our upfollowing function to the change event
if ( touched ) {
$dataListSelect.addEventListener( 'change', changeDataListSelect );
} else {
$dataListSelect.addEventListener( 'click', changeDataListSelect );
}
$dataListSelect.addEventListener( 'blur', changeDataListSelect );
$dataListSelect.addEventListener( 'keyup', changeDataListSelect );
// plus we'd like to prevent autocomplete on the input datalist field
$eventTarget.setAttribute( 'autocomplete', 'off' );
// WAI ARIA attributes
$eventTarget.setAttribute( 'role', 'textbox' );
$eventTarget.setAttribute( 'aria-haspopup', 'true' );
$eventTarget.setAttribute( 'aria-autocomplete', 'list' );
$eventTarget.setAttribute( 'aria-owns', list );
}
// toggle the visibility of the select according to previous checks
if ( visible ) {
$dataListSelect.removeAttribute( 'hidden' );
} else {
$dataListSelect.setAttributeNode( document.createAttribute( 'hidden' ) );
}
$dataListSelect.setAttribute( 'aria-hidden', ( !visible ).toString() );
// bind the keyup event on the related datalists input
switch( eventType ) {
case 'focus':
$eventTarget.addEventListener( 'keyup', inputInputList );
$eventTarget.addEventListener( 'focusOut', changesInputList, true );
break;
case 'blur':
$eventTarget.removeEventListener( 'keyup', inputInputList );
$eventTarget.removeEventListener( 'focusOut', changesInputList, true );
break;
}
}
}
};
// function regarding changes to the datalist polyfilling created select
var changeDataListSelect = function( event ) {
var $eventTarget = event.target,
eventTargetTagName = $eventTarget.tagName.toLowerCase();
// check for whether the events target was a select or an option
if ( eventTargetTagName && ( eventTargetTagName === 'select' || eventTargetTagName === 'option' ) ) {
var $select = ( eventTargetTagName === 'select' ) ? $eventTarget : $eventTarget.parentNode,
$datalist = $select.parentNode,
message = $datalist.title,
eventType = event.type,
// ENTER and ESC
visible = ( eventType === 'keyup' && ( event.keyCode !== keyENTER && event.keyCode !== keyESC ) );
// change or mouseup event or ENTER key
if ( eventType === 'change' || eventType === 'click' || ( eventType === 'keyup' && event.keyCode === keyENTER ) ) {
var list = $datalist.id,
$inputList = document.querySelector( 'input[list="' + list + '"]' ),
selectValue = $select.value;
// input the selects value into the input on a change within the list
if ( $inputList !== null && typeof( selectValue ) !== 'undefined' && selectValue.length > 0 && selectValue !== message ) {
var inputListValue = $inputList.value,
lastSeperator,
multipleEmails = ( $inputList.type === 'email' && $inputList.multiple );
// in case of type=email and multiple attribute, we need to set up the resulting inputs value differently
if ( multipleEmails && ( lastSeperator = inputListValue.lastIndexOf( ',' ) ) > -1 ) {
$inputList.value = inputListValue.slice( 0, lastSeperator ) + ',' + selectValue;
} else {
$inputList.value = selectValue;
}
// set the visibility to false afterwards, as we're done here
visible = false;
}
}
// toggle the visibility of the select according to previous checks
if ( visible ) {
$select.removeAttribute( 'hidden' );
} else {
$select.setAttributeNode( document.createAttribute( 'hidden' ) );
}
$select.setAttribute( 'aria-hidden', ( !visible ).toString() );
}
};
// binding the focus event - matching the input[list]s happens in the function afterwards
document.addEventListener( 'focus', changesInputList, true );
}
})();