Skip to content

Commit 3bd5d28

Browse files
committed
Call search on focus if input not empty and search not called yet
1 parent 65c8bf4 commit 3bd5d28

File tree

1 file changed

+24
-14
lines changed

1 file changed

+24
-14
lines changed

assets/js/app.js

+24-14
Original file line numberDiff line numberDiff line change
@@ -7,30 +7,20 @@ global.MonsieurBizInstantSearch = class {
77
keyUpTimeOut,
88
minQueryLength
99
) {
10+
let self = this;
1011
// Init a timeout variable to be used below
1112
var instantSearchTimeout = null;
1213
const searchInput = document.querySelector(searchInputSelector);
1314
if (!searchInput) {
1415
return;
1516
}
17+
self.searchCalled = false;
1618
searchInput.addEventListener('keyup', function (e) {
1719
clearTimeout(instantSearchTimeout);
1820
var query = e.currentTarget.value;
1921
var resultElement = e.currentTarget.closest(resultClosestSelector).querySelector(resultFindSelector);
2022
instantSearchTimeout = setTimeout(function () {
21-
if (query.length >= minQueryLength) {
22-
var httpRequest = new XMLHttpRequest();
23-
httpRequest.onload = function () {
24-
if (this.status === 200) {
25-
resultElement.innerHTML = this.responseText;
26-
resultElement.style.display = 'block';
27-
}
28-
};
29-
httpRequest.open("POST", instantUrl);
30-
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
31-
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
32-
httpRequest.send(new URLSearchParams({query: query}).toString());
33-
}
23+
self.callSearch(query, minQueryLength, instantUrl, resultElement);
3424
}, keyUpTimeOut);
3525
});
3626

@@ -45,12 +35,32 @@ global.MonsieurBizInstantSearch = class {
4535

4636
searchInput.addEventListener('focus', function (e) {
4737
var query = e.currentTarget.value;
48-
if (query !== '') {
38+
if (query !== '' && !self.searchCalled) {
39+
const resultElement = searchForm.querySelector(resultFindSelector);
40+
self.callSearch(query, minQueryLength, instantUrl, resultElement);
41+
self.searchCalled = true;
42+
} else if (query !== '') {
4943
const resultElement = searchForm.querySelector(resultFindSelector);
5044
resultElement.style.display = 'block';
5145
}
5246
});
5347
}
48+
49+
callSearch (query, minQueryLength, instantUrl, resultElement) {
50+
if (query.length >= minQueryLength) {
51+
var httpRequest = new XMLHttpRequest();
52+
httpRequest.onload = function () {
53+
if (this.status === 200) {
54+
resultElement.innerHTML = this.responseText;
55+
resultElement.style.display = 'block';
56+
}
57+
};
58+
httpRequest.open("POST", instantUrl);
59+
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
60+
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
61+
httpRequest.send(new URLSearchParams({ query: query }).toString());
62+
}
63+
}
5464
}
5565

5666
document.addEventListener("DOMContentLoaded", function() {

0 commit comments

Comments
 (0)