forked from intern2grow/wikipedia-search-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
45 lines (42 loc) · 1.45 KB
/
script.js
File metadata and controls
45 lines (42 loc) · 1.45 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
let resultsContainer = document.getElementsByClassName("container")[0];
let debounceTimer;
const debounce = (func, delay) => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func(), delay);
};
const validateInput = (el) => {
debounce(() => {
if (el.value === "") {
resultsContainer.innerHTML = "<p>Type something in the above search input</p>";
} else {
generateResults(el.value, el);
}
}, 500);
};
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>";
}
});
};