metasearch/src/web/assets/script.js

38 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-12-20 09:28:38 +00:00
const searchInputEl = document.getElementById("search-input");
2023-12-20 23:45:16 +00:00
// add a datalist after the search input
2023-12-20 09:28:38 +00:00
const datalistEl = document.createElement("datalist");
datalistEl.id = "search-input-datalist";
searchInputEl.setAttribute("list", datalistEl.id);
searchInputEl.insertAdjacentElement("afterend", datalistEl);
// update the datalist options on input
searchInputEl.addEventListener("input", async (e) => {
const value = e.target.value;
2023-12-20 23:17:46 +00:00
const res = await fetch(`/autocomplete?q=${encodeURIComponent(value)}`).then(
(res) => res.json()
);
2023-12-20 09:28:38 +00:00
const options = res[1];
datalistEl.innerHTML = "";
options.forEach((option) => {
const optionEl = document.createElement("option");
optionEl.value = option;
datalistEl.appendChild(optionEl);
});
});
2023-12-21 05:17:39 +00:00
// if the user starts typing but they don't have focus on the input, focus it
document.addEventListener("keydown", (e) => {
// must be a letter or number
2023-12-21 05:48:28 +00:00
if (
e.key.match(/^[a-z0-9]$/i) &&
!searchInputEl.matches(":focus") &&
!e.ctrlKey &&
!e.metaKey
) {
2023-12-21 05:17:39 +00:00
searchInputEl.focus();
}
});