Skip to content

Commit

Permalink
Call search on focus if input not empty and search not called yet
Browse files Browse the repository at this point in the history
  • Loading branch information
maximehuran committed Aug 16, 2023
1 parent 65c8bf4 commit 3bd5d28
Showing 1 changed file with 24 additions and 14 deletions.
38 changes: 24 additions & 14 deletions assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,20 @@ global.MonsieurBizInstantSearch = class {
keyUpTimeOut,
minQueryLength
) {
let self = this;
// Init a timeout variable to be used below
var instantSearchTimeout = null;
const searchInput = document.querySelector(searchInputSelector);
if (!searchInput) {
return;
}
self.searchCalled = false;
searchInput.addEventListener('keyup', function (e) {
clearTimeout(instantSearchTimeout);
var query = e.currentTarget.value;
var resultElement = e.currentTarget.closest(resultClosestSelector).querySelector(resultFindSelector);
instantSearchTimeout = setTimeout(function () {
if (query.length >= minQueryLength) {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function () {
if (this.status === 200) {
resultElement.innerHTML = this.responseText;
resultElement.style.display = 'block';
}
};
httpRequest.open("POST", instantUrl);
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send(new URLSearchParams({query: query}).toString());
}
self.callSearch(query, minQueryLength, instantUrl, resultElement);
}, keyUpTimeOut);
});

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

searchInput.addEventListener('focus', function (e) {
var query = e.currentTarget.value;
if (query !== '') {
if (query !== '' && !self.searchCalled) {
const resultElement = searchForm.querySelector(resultFindSelector);
self.callSearch(query, minQueryLength, instantUrl, resultElement);
self.searchCalled = true;
} else if (query !== '') {
const resultElement = searchForm.querySelector(resultFindSelector);
resultElement.style.display = 'block';
}
});
}

callSearch (query, minQueryLength, instantUrl, resultElement) {
if (query.length >= minQueryLength) {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function () {
if (this.status === 200) {
resultElement.innerHTML = this.responseText;
resultElement.style.display = 'block';
}
};
httpRequest.open("POST", instantUrl);
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send(new URLSearchParams({ query: query }).toString());
}
}
}

document.addEventListener("DOMContentLoaded", function() {
Expand Down

0 comments on commit 3bd5d28

Please sign in to comment.