-
Notifications
You must be signed in to change notification settings - Fork 4
/
script.js
55 lines (41 loc) · 1.44 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
52
53
54
55
// JavaScript Document
let resultsList = document.getElementById('resultsList');
let searchForm = document.getElementById('searchForm');
let searchInput = document.getElementById('searchInput');
searchForm.addEventListener('submit', (e)=> {
e.preventDefault();
displaySearchResults(searchInput.value);
})
function displaySearchResults(x){
let url = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=${x}`;
console.log(url);
fetch(url)
.then(function(response) {
return (response.json());
})
.then(function(data){
let resultsArray = data.query.search;
resultsOnPage(resultsArray);
})
.catch(function () {
console.log('An error occured');
});
}
function resultsOnPage(myArray){
resultsList.innerHTML = " ";
resultsList.insertAdjacentHTML('beforeend', `<h2>Search Results for ${searchInput.value} </h2>`);
myArray.forEach(function(item){
let itemTitle = item.title;
let itemSnippet = item.snippet;
let itemUrl = encodeURI(`https://en.wikipedia.org/wiki/${item.title}`);
resultsList.insertAdjacentHTML('beforeend',
`<div class="resultItem">
<h3 class="resultTitle">
<a href="${itemUrl}" target="_blank" rel="noopener">${itemTitle}</a>
</h3>
<p class="resultSnippet"><a href="${itemUrl}" target="_blank" rel="noopener">
${itemSnippet}</a></p>
</div>`
);
})
}