forked from intern2grow/wikipedia-search-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
51 lines (48 loc) · 1.71 KB
/
script.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
let resultsContainer = document.getElementsByClassName("container")[0];
// update the validateInput function to use the debounced version of generateResults
const validateInput = (el) => {
if (el.value === "") {
resultsContainer.innerHTML =
"<p>Type something in the above search input</p>";
} else {
debouncedGenerateResults(el.value, el);
}
};
// define a simple debounce function
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
const generateResults = (searchValue, inputField) => {
fetch(
"https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=" +
searchValue
)
.then((response) => response.json())
.then((data) => {
let results = data.query.search;
let numberOfResults = data.query.search.length;
resultsContainer.innerHTML = "";
for (let i = 0; i < numberOfResults; i++) {
let result = document.createElement("div");
result.classList.add("results");
result.innerHTML = `
<div>
<h3>${results[i].title}</h3>
<p>${results[i].snippet}</p>
</div>
<a href="https://en.wikipedia.org/?curid=${results[i].pageid}" target="_blank">Read More</a>
`;
resultsContainer.appendChild(result);
}
if (inputField.value === "") {
resultsContainer.innerHTML =
"<p>Type something in the above search input</p>";
}
});
};
// create a debounced version of the generateResults function
const debouncedGenerateResults = debounce(generateResults, 300);