-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
99 lines (86 loc) · 3.12 KB
/
search.js
File metadata and controls
99 lines (86 loc) · 3.12 KB
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
var srch;
$(document).ready(function () {
srch = new Search();
})
function Search() {
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
function keyUp(e) {
var search = $(this).val();
delay(function () {
if (search.length == 0) {
return;
}
fun(search).then(function (result) {
var html = "";
for (var i = 0; i < result.length; i++) {
html += "<div class='search-item'>" + result[i] + "</div>";
}
$(".search-results").html(html);
searchResults.show();
}, function (err) {
console.error(err);
});
}, timeout);
}
this.setup = function (element, callback, timeout = 450) {
// error handling
var errors = [];
if (element == null) { errors.push("Element must be supplied."); }
else if (!$(element).is("input[type=text]")) {
errors.push("Supplied element is not a textual input.")
}
if (callback == null) { errors.push("Callback must be supplied.") }
if (errors.length > 0) {
for (var i in errors) {
console.error(errors[i]);
}
return;
}
// execution
var searchResults = $(".search-results");
searchResults.css('width', $(element).outerWidth() - 2); // -2 for the border width
$(element).keyup(function (e) {
var search = $(this).val();
delay(function () {
if (search.length == 0) {
searchResults.hide();
return;
}
callback(search).then(function (result) {
var html = "";
for (var i in result) {
html += "<div class='search-item'>" + result[i] + "</div>";
}
// set location
var top = $(element).offset().top + $(element).outerHeight(true) - parseInt($(element).css('margin-bottom')) - $(document).scrollTop();
var left = $(element).offset().left + parseInt($(element).css('margin-left')) - $(document).scrollLeft();
searchResults.css('top', top);
searchResults.css('left', left);
searchResults.html(html);
searchResults.show();
}, function (err) {
console.error(err);
});
}, timeout);
});
// remove container on scroll/mouseup events
$(document).scroll(function () {
searchResults.hide();
});
$(document).mouseup(function (e) {
if (!searchResults.is(e.target) && searchResults.has(e.target).length === 0) {
searchResults.hide();
}
});
}
function setup() {
$("body").append("<div class='search-results'></div>")
}
setup();
}