-
Notifications
You must be signed in to change notification settings - Fork 51
/
searchbox.js
77 lines (61 loc) · 1.87 KB
/
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
// Author: Ryan Heath
// http://rpheath.com
(function($) {
$.searchbox = {}
$.extend(true, $.searchbox, {
settings: {
url: '/search',
param: 'query',
dom_id: '#results',
delay: 100,
loading_css: '#loading'
},
loading: function() {
$($.searchbox.settings.loading_css).show()
},
resetTimer: function(timer) {
if (timer) clearTimeout(timer)
},
idle: function() {
$($.searchbox.settings.loading_css).hide()
},
process: function(terms) {
var path = $.searchbox.settings.url.split('?'),
query = [$.searchbox.settings.param, '=', terms].join(''),
base = path[0], params = path[1], query_string = query
if (params) query_string = [params.replace('&', '&'), query].join('&')
$.get([base, '?', query_string].join(''), function(data) {
$($.searchbox.settings.dom_id).html(data)
})
},
start: function() {
$(document).trigger('before.searchbox')
$.searchbox.loading()
},
stop: function() {
$.searchbox.idle()
$(document).trigger('after.searchbox')
}
})
$.fn.searchbox = function(config) {
var settings = $.extend(true, $.searchbox.settings, config || {})
$(document).trigger('init.searchbox')
$.searchbox.idle()
return this.each(function() {
var $input = $(this)
$input
.focus()
.ajaxStart(function() { $.searchbox.start() })
.ajaxStop(function() { $.searchbox.stop() })
.keyup(function() {
if ($input.val() != this.previousValue) {
$.searchbox.resetTimer(this.timer)
this.timer = setTimeout(function() {
$.searchbox.process($input.val())
}, $.searchbox.settings.delay)
this.previousValue = $input.val()
}
})
})
}
})(jQuery);