-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
52 lines (51 loc) · 1.58 KB
/
Copy pathapp.js
File metadata and controls
52 lines (51 loc) · 1.58 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
48
49
50
51
52
let input = document.querySelector("#input");
let btn = document.querySelector("#search");
let apikey = "";
let notfound = document.querySelector(".not_found");
let def = document.querySelector(".def");
let loading = document.querySelector(".loader");
// When button is clicked
btn.addEventListener("click", function (e) {
e.preventDefault();//prevent to reload the page
let word = input.value;
// If input is blank
if (word === "") {
alert("⚠ Please Type a Word Before Searching ⚠");
return;
}
// Function call
getData(word);
});
async function getData(word) {
// API Fetch
loading.style.display = "block";
notfound.innerHTML = "";
def.innerHTML = "";
const response = await fetch(
`https://www.dictionaryapi.com/api/v3/references/learners/json/${word}?key=${apikey}`
);
const data = await response.json();
// If no data is found return No Result
if (!data.length) {
loading.style.display = "none";
notfound.innerText = "No Result Found";
return;
}
// If result is suggestion
if (typeof data[0] === "string") {
loading.style.display = "none";
let heading = document.createElement("h4");
heading.innerHTML = "Did you mean?";
notfound.appendChild(heading);
data.forEach((element) => {
let suggestion = document.createElement("span");
suggestion.classList.add("suggested");
suggestion.innerHTML = element;
notfound.appendChild(suggestion);
});
}
// If result is Found
loading.style.display = "none";
let defination = data[0].shortdef[0];
def.innerHTML = `Meaning of ${word} : ` + defination;
}