-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.searchbox.js
85 lines (75 loc) · 1.92 KB
/
jquery.searchbox.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
(function($){
$.fn.searchbox = function(options) {
var defaults = {
resultsArea: '#s-results',
trigger: function(keyword) {
console.log('Syncing');
this.updateResultsArea('No result matching your search.');
}
};
var searchBox = new SearchBox($.extend(defaults, options));
$(this)
.keyup(function() {
var keyword = $(this).val();
searchBox.search(keyword);
})
.blur(function() {
searchBox.isTyping = false;
setTimeout(function() { searchBox.hideResultsArea(); }, 500);
})
.focus(function() {
searchBox.isTyping = true;
if($(this).val() != '') {
searchBox.resultsArea.show();
}
});
};
function SearchBox(options) {
this.resultsArea = $(options.resultsArea);
this.trigger = options.trigger;
this.isHover = false;
this.isTyping = false;
this.keyword = ''; // TODO
this.init();
};
SearchBox.prototype = {
constructor: SearchBox,
init: function() {
var self = this;
this.resultsArea.hover(
function() {
self.isHover = true;
self.resultsArea.show();
},
function() {
self.isHover = false;
setTimeout(function() { self.hideResultsArea(); },500);
}
);
},
search: function(keyword) {
if($.trim(keyword) != '') {
this.keyword = keyword;
clearTimeout(this.searchEvent);
var self = this;
this.searchEvent = setTimeout(function() {
self.trigger(keyword);
}, 500);
} else {
this.resultsArea.hide().empty();
}
},
updateResultsArea: function(results) {
this.show();
this.resultsArea.html(results);
},
show: function() {
this.resultsArea.show();
},
hideResultsArea: function() {
if(!this.isHover && !this.isTyping) {
this.resultsArea.hide();
}
}
}
})( jQuery );