-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdropdown_suggest_plugin.js
executable file
·253 lines (213 loc) · 7.7 KB
/
dropdown_suggest_plugin.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
(function ($) {
// Private variables
var $dropdown = $('<div></div>').addClass('dropdown_suggest');
var _settings;
var _url;
var _cacheSize = 30;
var _cachedResults = {};
var _cachedResultsKeys = [];
var _cachedQueryResult = [];
var _oldInput;
$.fn.dropdown_suggest = function(url, options) {
// -------------------- Init plugin --------------------
_url = url;
_settings = $.extend({
requestType: 'POST',
dataType: 'json',
limit: 10,
fade_time: 100,
clientside_filter: true,
select_callback: function() {},
}, options);
var $input = this;
// -------------------- Event Bindings --------------------
$input.on('click keyup', function(event) {
event.preventDefault();
var input = $input.val();
// If arrow keys or enter are pressed, don't reload dropdown. If dropdown is hidden, down arrow opens it
if(event.which == 40 && !$dropdown[0].hidden || event.which == 39 ||
event.which == 38 || event.which == 37 || event.which == 13) {
return;
}
// Use the query cache if we are using clientside filtering,
// and the new query string will give a subset of the results of the old one,
// otherwise clear it
var useQueryCache = _settings.clientside_filter &&
new RegExp('^' + _oldInput + '.*').test(input);
if(!useQueryCache) {
_cachedQueryResult = null;
}
// If the input is not empty, query for matching suggestions
if(input) {
$dropdown.data('selected_index', 'none');
// If there are cached results, skip the ajax call
if(_cachedResults[input]) {
var suggestions = _cachedResults[input];
populate_dropdown(suggestions);
// If the same set of data is being filtered, use the cached query results
} else if(useQueryCache && _cachedQueryResult) {
var suggestions = filterData(_cachedQueryResult, input);
cacheResults(input, suggestions);
populate_dropdown(suggestions);
// Perform the ajax call
} else {
ajax_call(input).done(function(data) {
if(data && data.length > 0) {
if(_settings.clientside_filter) {
data = filterData(data, input);
}
cacheResults(input, data);
populate_dropdown(data);
} else {
$dropdown.hide(_settings.fade_time);
}
});
}
// If the cache size exceeds the size limit, delete the oldest entry
if(_cachedResultsKeys.length > _cacheSize) {
var key = _cachedResultsKeys.shift();
delete _cachedResults[key];
}
} else {
$dropdown.hide(_settings.fade_time);
}
});
// Update selection in dropdown if the arrow keys are pressed
$input.on('keydown', function(event) {
var input = $input.val();
// If the input was empty, clear the query cache to start anew
if(!input) {
_cachedQueryResult = null;
}
_oldInput = input;
var down = event.which == 40; // down arrow pressed
var up = event.which == 38; // up arrow pressed
if(!up && !down) return;
event.preventDefault();
var index = $dropdown.data('selected_index');
var options = $dropdown.find('li');
// If the user mouses over the dropdown, selection is cleared
// Then if arrow pressed, set selected to first
if(index == 'none') {
index = 0;
} else {
if(down) {
index = (index + 1) % options.length;
} else if(up) {
index = (index - 1) % options.length;
}
}
// Update dropdown selected index
$dropdown.data('selected_index', index);
options.removeAttr('selected');
options.eq(index).attr('selected', 'selected');
});
// If the mouse enters a dropdown element, highlight it and clear the selection
$(document).on('mouseenter', '.dropdown_suggest li', function(event) {
$dropdown.data('selected_index', 'none');
$dropdown.find('li').removeAttr('selected');
$(event.target).attr('selected', 'selected');
});
// Hide the dropdown if clicked outside
$(document).on('click', function(event) {
if(!$input.is(event.target)) {
$dropdown.hide(_settings.fade_time);
}
});
// Select an item either by clicking on it or by pressing enter
$dropdown.on('click', function(event) {
// Stop link activation
event.preventDefault();
var selected_val = $(event.target).data('id');
$input.val(selected_val);
// Hide dropdown
$dropdown.hide(_settings.fade_time, function() {
// Perform user defined callback
_settings.select_callback(selected_val);
})
});
$input.keypress(function(event) {
// Pressed enter
if(event.which == 13) {
event.preventDefault();
if(!$dropdown[0].hidden && $dropdown.data('selected_index') !== 'none') {
// Set value of input to the selected dropdown item
var selected_val = $dropdown.find('li').eq($dropdown.data('selected_index')).data('id');
$input.val(selected_val);
// Hide dropdown
$dropdown.hide(_settings.fade_time, function() {
// Perform user defined callback
_settings.select_callback(selected_val);
});
}
}
});
// -------------------- Finalize elements --------------------
$dropdown.hide();
$input.after($dropdown);
$input.attr('autocomplete', 'off')
return $input;
};
// -------------------- Functions --------------------
/*
* Filter the array according to the match string
*/
function filterData(data, match_string) {
return data.filter(function(entry) {
return new RegExp('^' + match_string + '.*').test(entry)
});
}
/*
* Cache the results
*/
function cacheResults(input, suggestions) {
_cachedQueryResult = suggestions;
_cachedResults[input] = suggestions;
_cachedResultsKeys.push(input);
}
/**
* Populates dropdown with the filtered array
*/
function populate_dropdown(entries) {
entries = entries.slice(0, _settings.limit);
var list = $('<ul></ul>').addClass('list-group');
entries.forEach(function(entry) {
list.append($('<li></li>').text(entry).data('id', entry).addClass('list-group-item'));
});
$dropdown.html(list).show(_settings.fade_time, function() {
// Reset dropdown selected index
$dropdown.data('selected_index', 0);
var options = $dropdown.find('li');
options.removeAttr('selected');
options.eq(0).attr('selected', 'selected');
});
}
/*
* Shows the dropdown error message
*/
function show_dropdown_error(err) {
var list = $('<ul></ul>').addClass('list-group');
list.append($('<li></li>').text(entry).data('id', entry).addClass('list-group-item'));
$dropdown.html(list).show(_settings.fade_time, function() {
// Reset dropdown selected index
$dropdown.data('selected_index', 0);
var options = $dropdown.find('li');
options.removeAttr('selected');
options.eq(0).attr('selected', 'selected');
});
}
/*
* Makes an ajax call to the specified url
*/
function ajax_call(match_string) {
return $.ajax({
type: _settings.requestType,
url: _url,
dataType: _settings.dataType,
data: {
match_string: match_string,
limit: _settings.limit,
}
});
}
} (jQuery));