-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiki.js
50 lines (44 loc) · 1.56 KB
/
wiki.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
function handleSubmit(event) {
// prevent page from reloading when form is submitted
event.preventDefault();
// get the value of the input field
const input = document.querySelector(".searchForm-input").value;
// remove whitespace from the input
const searchQuery = input.trim();
// call `fetchResults` and pass it the `searchQuery`
fetchResults(searchQuery);
}
function fetchResults(searchQuery) {
const endpoint = `https://fr.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=10&srsearch=${searchQuery}`;
fetch(endpoint)
.then((response) => response.json())
.then((data) => {
const results = data.query.search;
displayResults(results);
})
.catch(
() =>
(document.querySelector(".searchForm-input").value =
"Please enter a search term.")
);
//.catch(() => console.log('An error occured'));
}
function displayResults(results) {
const searchResults = document.querySelector(".searchResults");
searchResults.innerHTML = "";
results.forEach((result) => {
const url = encodeURI(`https://fr.wikipedia.org/wiki/${result.title}`);
searchResults.insertAdjacentHTML(
"beforeend",
`<div class="resultItem">
<h3 class="resultItem-title">
<a href="${url}" target="_blank" rel="noopener">${result.title}</a>
</h3>
<span class="resultItem-snippet">${result.snippet}</span><br>
<a href="${url}" class="resultItem-link" target="_blank" rel="noopener">${url}</a>
</div>`
);
});
console.log(results);
}
document.querySelector(".searchForm").addEventListener("submit", handleSubmit);