-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
47 lines (42 loc) · 1.72 KB
/
script.js
File metadata and controls
47 lines (42 loc) · 1.72 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
46
47
const input = document.getElementById("input");
const infoText = document.getElementById("info-text");
const meaningContainer = document.getElementById("meaning-container");
const title = document.getElementById("title");
const meaning = document.getElementById("meaning");
const audio = document.getElementById("audio");
async function fetchAPI(word){
// allows you to get the possible error from an API request
try {
infoText.style.display = "block";
infoText.innerText = `Searching for the meaning of ${word}`
const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`
const result = await fetch(url).then((res)=>res.json())
console.log(result);
if (result.title) {
meaningContainer.style.display = "block";
infoText.style.display = "none";
title.innerText = word;
meaning.innerText = "N/A";
audio.style.display = "none";
} else {
infoText.style.display = "none";
meaningContainer.style.display = "block";
audio.style.display = "inline-flex";
title.innerText = result[0].word;
meaning.innerText = result[0].meanings[0].definitions[0].definition;
audio.src = result[0].phonetics[0].audio;
}
} catch (error) {
console.log(error);
infoText.innerText = `Sorry pal, we couldn't find meaning of ${word} You can try the search later `;
}
}
input.addEventListener("keyup", (e)=> {
// console.log anything we enter
// console.log(e.target.value);
// shows the key e.g enter, backspace
// console.log(e.key);
if(e.target.value && e.key === "Enter"){
fetchAPI(e.target.value)
}
})