forked from rpheath/searchbox
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hsearchbox.js
109 lines (97 loc) · 2.83 KB
/
hsearchbox.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
// Author: Ryan Heath
// http://rpheath.com
// Mirs edited
(function($) {
function HSearchBox(options){
var defaults = {
url: '/search',
param: 'query',
dom_id: '#livesearch_results',
delay: 250,
minChars: 2,
loading_css: '#livesearch_loading',
del_id: '#livesearch_del',
form_id: '#livesearch_form',
dataType: 'text',
onInitSearch: function(){},
onStartSearch: function(){},
onFinishSearch: function(){}u
}
this.settings = $.extend({}, defaults, options || {})
this.loading = function() {
$(this.settings.loading_css).show()
}
this.idle = function() {
$(this.settings.loading_css).hide()
}
this.start = function() {
this.loading()
this.settings.onStartSearch()
}
this.stop = function() {
this.idle()
this.settings.onFinishSearch()
}
this.kill = function() {
$(this.settings.dom_id).fadeOut(50)
$(this.settings.dom_id).html('')
$(this.settings.del_id).fadeOut(100)
}
this.reset = function() {
$(this.settings.dom_id).html('')
$(this.settings.dom_id).fadeOut(50)
$(this.settings.form_id).val('')
$(this.settings.del_id).fadeOut(100)
}
this.resetTimer = function(timer) {
if (timer) clearTimeout(timer)
}
this.process = function(terms) {
var currentSearchBox = this
if (/\S/.test(terms)) {
$.ajax({
type: 'GET',
dataType : currentSearchBox.settings.dataType,
url: currentSearchBox.settings.url,
data: {
search: terms.trim()
},
complete: function(data) {
$(currentSearchBox.settings.del_id).fadeIn(50)
$(currentSearchBox.settings.dom_id).html(data.responseText)
if (!$(currentSearchBox.settings.dom_id).is(':empty')) {
$(currentSearchBox.settings.dom_id).fadeIn(100)
}
currentSearchBox.stop()
}
})
return false
} else {
currentSearchBox.kill()
}
}
}
$.fn.hsearchbox = function(configs) {
var hsearchbox = new HSearchBox(configs)
hsearchbox.settings.onInitSearch()
hsearchbox.idle()
return this.each(function() {
var $input = $(this)
$input
.keyup(function() {
if ($input.val() != this.previousValue) {
if (/\S/.test($input.val().trim()) && $input.val().trim().length > hsearchbox.settings.minChars) {
hsearchbox.resetTimer(this.timer)
this.timer = setTimeout(function() {
hsearchbox.start()
hsearchbox.process($input.val())
}, hsearchbox.settings.delay)
} else {
hsearchbox.kill()
}
this.previousValue = $input.val()
}
})
})
}
})(jQuery)