forked from honza/suggestr.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.suggestr.js
114 lines (90 loc) · 2.39 KB
/
jquery.suggestr.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
/*
* Suggestr - the dead simple autocompleter for jQuery
* Author: Honza Pokorny
* Usage: $('#input').suggestr(['John', 'Peter', 'Mark']);
* URL: https://github.com/honza/suggestr.js
* License: BSD
*
*/
(function($) {
var keyMap = {
up: 38,
down: 40,
enter: 13
};
var activeCss = {
listStyle: 'none',
backgroundColor: '#ececec'
};
var inactiveCss = {
listStyle: 'none',
backgroundColor: '#fff'
};
var boxCss = {
width: '200px',
position: 'absolute'
};
$.fn.suggestr = function(data) {
var ui, that, value;
that = this;
ui = $('<div id="suggestr-div"></div>');
ui.css(boxCss);
ui.data('active', 0);
ui.delegate('li', 'mouseover', function() {
$(this).css(activeCss);
});
ui.delegate('li', 'mouseout', function() {
$(this).css(inactiveCss);
});
ui.delegate('li', 'click', function() {
var val = $(this).text();
that.val(val);
reset();
});
function moveSelection(direction) {
var index = ui.data('active');
if (direction == keyMap.up)
var newIndex = index - 1;
else
var newIndex = index + 1;
if (-1 < newIndex && newIndex < ui.children().length) {
ui.children().each(function(i, item) {
$(item).css(inactiveCss);
});
$(ui.children()[newIndex]).css(activeCss);
ui.data('active', newIndex);
}
}
function reset() {
ui.data('active', 0);
ui.children().remove();
}
this.keyup(function(k) {
if (k.keyCode == keyMap.enter) {
var val = $(ui.children()[ui.data('active')]).text();
that.val(val);
reset();
return;
}
if (k.keyCode == keyMap.up || k.keyCode == keyMap.down) {
moveSelection(k.keyCode);
return false;
}
ui.children().remove();
value = that.val().toLowerCase();
if (!value.length)
return;
$.each(data, function(index, item) {
if (item.toLowerCase().indexOf(value) > -1) {
var regx = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + value + ")(?![^<>]*>)(?![^&;]+;)", "gi");
item = item.replace(regx, "<strong>$1</strong>");
var x = $('<li>' + item + '</li>');
$(x).css(inactiveCss);
ui.append(x);
}
});
that.after(ui);
ui.children().first().css(activeCss);
});
};
})(jQuery);