-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathjquery.selectify.js
More file actions
441 lines (310 loc) · 10.2 KB
/
jquery.selectify.js
File metadata and controls
441 lines (310 loc) · 10.2 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
/*jshint jquery:true */
/**
* Selectify - an unobtrusive select overlay that reproduces the
* native <select> element experience Pretty Well(TM).
*
* by James Ducker <james.ducker+js@gmail.com>
*
* Works with jQuery >= 1.7
*
* "Add-and-forget" - manipulate your underlying <select> element
* and changes are immediately propagated to Selectify's overlay.
*
* Project home: https://github.com/jamesinc/selectify
* Issue tracker: https://github.com/jamesinc/selectify/issues
*/
( function ( $ ) {
"use strict";
// Got some default options up in here.
var defaults = {
duration: 50,
autoWidth: true,
btnText: "▼",
classes: {
container: "sl-container",
placeholderContainer: "sl-placeholder-container",
placeholder: "sl-placeholder",
btn: "sl-button",
options: "sl-options",
selected: "sl-selected",
open: "sl-open"
}
};
/**
* Call against any select element or collection containing select elements
* Non-select elements will be ignored.
* @param {Object} options Options to pass to the plugin.
* Valid options are:
* duration (number, milliseconds) slide up/slide
* down animation duration.
* classes.container
* Class name of the container element
* classes.placeholder
* Class name of the placeholder element
* (holds the current value of the select)
* classes.options
* Class name of the dropdown
* container <ul> element
* classes.selected
* Class name of the option that is currently
* selected. Applied to <a> inside <li>
* inside options <ul>.
* classes.open
* Added to container element when the
* options list is open.
*
* @return {jQuery} The jQuery object.
*/
$.fn.selectify = function ( options ) {
var settings,
// Maintain a dictionary of values in the select
// so they can be matched as the user types
Dictionary = function ( select ) {
var optionsHtml = "",
searchString = "",
searchTimer = null,
dict = { },
clearSearchString = function ( ) {
searchString = "";
},
// JS doesn't notify us when 3rd-party code modifies the options
// list, so we get the options HTML as a string and compare it
// to the last one we stored. If they're different, we rebuild
// the dictionary.
rebuild = function ( ) {
if ( select.html() !== optionsHtml ) {
$.each( select.find( "option" ), function ( ) {
var el = $( this );
if ( el.text().length ) {
dict[ el.text() ] = el.val();
}
});
optionsHtml = select.html();
}
},
// Restarts the countdown to clear the search string
resetSearch = function ( ) {
clearTimeout( searchTimer );
searchTimer = setTimeout( clearSearchString, 1000 );
};
return {
find: function ( text ) {
var textLength,
selectedOption = $( select.find("option").get(select.get(0).selectedIndex) ),
result = false;
rebuild();
resetSearch();
searchString += text;
textLength = searchString.length;
if ( !selectedOption.length || selectedOption.text().substr(0, textLength).toUpperCase() !== searchString ) {
if ( textLength ) {
$.each( dict, function ( key, value ) {
if ( key.substr(0, textLength).toUpperCase() === searchString ) {
result = value;
return false;
}
});
}
}
return result;
},
clear: function ( ) {
clearTimeout( searchTimer );
clearSearchString();
}
};
};
options = options || { };
// Merge defaults and options to make settings
settings = $.extend( true, { }, defaults, options );
// Setup each <select> in the provided collection.
this.each( function ( ) {
var el = $( this ),
dict = new Dictionary( el ),
self = this,
options,
container, placeholderContainer,
placeholder, btn, list, anchors;
// If current element is not a <select> element, skip it.
if ( !el.is("select") ) {
return;
}
// Check to see if this element has already been selectified(TM)
if ( el.data("sl") === true ) {
// Remove old selectifications from the element
el.next( "." + settings.classes.container ).remove();
}
// Get collection of <option> elements
options = el.find( "option" );
// Create container element for the new UI
container = $( "<div/>", {
"class": settings.classes.container,
css: {
"position": "relative"
}
});
placeholderContainer = $( "<div/>", {
"class": settings.classes.placeholderContainer,
tabindex: 0
});
// Create placeholder element to display the select's
// current value
placeholder = $( "<div/>", {
"class": settings.classes.placeholder
});
btn = $( "<div />", {
"class": settings.classes.btn,
text: settings.btnText,
css: {
position: "absolute",
right: 0,
top: 0,
height: "100%"
}
});
placeholderContainer.append( placeholder, btn );
// Create the list element for options
list = $( "<ul/>", {
"class": settings.classes.options,
css: {
position: "absolute",
left: 0
}
});
// Go through each option and add it to the list
options.each( function ( ) {
var self = $( this ),
a = $( "<a/>", {
href: "#",
text: self.text(),
css: {
"white-space": "nowrap"
},
click: function ( e ) {
e.preventDefault();
if ( el.val() !== self.val() ) {
placeholder.text( self.text() );
list.find( "a" ).removeClass( settings.classes.selected );
a.addClass( settings.classes.selected );
el
.val( self.val() )
.trigger( "change", [ { sl: true }] );
}
list.slideUp( settings.duration );
container.removeClass( settings.classes.open );
}
}),
li = $( "<li/>" );
li.append( a );
list.append( li );
});
// Handle list open/close.
placeholderContainer.on( "click", function ( e ) {
e.preventDefault();
list.slideToggle( settings.duration );
container.toggleClass( settings.classes.open );
el.trigger( "change" );
});
placeholderContainer.on( "keydown", function ( e ) {
var key = e.which,
keyChar = String.fromCharCode( key ),
match,
intercept = false,
currentIndex = self.selectedIndex;
// Down arrow, right arrow
if ( key === 40 || key === 39 ) {
intercept = true;
self.selectedIndex = Math.min( options.length - 1, self.selectedIndex + 1 );
}
// Up arrow, left arrow
if ( key === 38 || key === 37 ) {
intercept = true;
self.selectedIndex = Math.max( 0, self.selectedIndex - 1 );
}
// Stop processing if it's a command key (i.e. directional arrow)
if ( intercept ) {
e.preventDefault();
if ( currentIndex !== self.selectedIndex ) {
dict.clear();
el.trigger( "change" );
}
return false;
}
// Enter key, space bar
// Causes the options list to close (if it's open)
if ( key === 13 || key === 32 ) {
list.slideUp( settings.duration );
}
// Match other keystrokes - used for typing values into the select
// and having it match them
if ( /[a-zA-Z0-9-_ !@#$%^&*\(\)+\/\\?><;:'"|]/.test(keyChar) ) {
match = dict.find( keyChar );
if ( match && el.val() !== match ) {
el
.val( match )
.trigger( "change" );
}
}
});
placeholderContainer.on( "selectstart", function ( ) {
return false;
});
// Close the list if the user clicks elsewhere on the page.
$( document ).on( "mouseup", function ( e ) {
if ( !container.has( e.target ).length ) {
list.slideUp( settings.duration );
container.removeClass( settings.classes.open );
}
});
// Listen for change events on the original select element
el.on( "change", function ( e, src ) {
var index = this.selectedIndex,
listScrollOffset = Math.abs( list.scrollTop() ),
selectedAnchor = $( anchors.get(index) ),
positionOffset = parseInt(list.css("border-top-width"), 10),
selectionOffset = selectedAnchor.offset().top - anchors.first().offset().top;
// Scroll the options list up if selection is above the visible
// portion of the list
if ( selectionOffset < listScrollOffset ) {
list.clearQueue().animate({
scrollTop: positionOffset + selectionOffset
}, settings.duration);
} else if ( selectionOffset > listScrollOffset +
list.height() - selectedAnchor.outerHeight() )
{
list.clearQueue().animate({
scrollTop: positionOffset + selectionOffset - list.height() + selectedAnchor.outerHeight()
}, settings.duration);
}
// Don't do anything if the event was originally propagated by this plugin
if ( src && src.sl ) {
return;
}
placeholder.text( $(options.get(index)).text() );
anchors.removeClass( settings.classes.selected );
selectedAnchor.addClass( settings.classes.selected );
});
// Get anchors list
anchors = list.find("a");
// Set initial placeholder text
placeholder.text( $(options.get(el[0].selectedIndex)).text() );
// Set initial anchor styling
$( anchors.get(el[0].selectedIndex) ).addClass( settings.classes.selected );
if ( settings.autoWidth ) {
placeholder.width( el.width() );
}
// Add our elements to the page
container.append( placeholderContainer, list );
el
.hide()
.after( container )
.data( "sl", true );
// Add a height offset to the list
list
.hide()
.css( "top", container.outerHeight() );
});
// return the jQuery object
return this;
};
}( jQuery ));