-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
90 lines (77 loc) · 2.32 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
let input = document.querySelector("#input");
let searchBtn = document.querySelector("#search");
let apiKey = "1189cfc7-1511-453f-89e5-34d6fd00ecd1";
let notFound = document.querySelector(".not__found");
let defBox = document.querySelector(".def");
let audioBox = document.querySelector(".audio");
let loading = document.querySelector(".loading");
searchBtn.addEventListener("click", dict);
function dict(e) {
e.preventDefault();
let word = input.value;
if (word === "") {
alert("Word is required");
return;
}
ClearOutput();
getData(word);
}
function search(e) {
console.log(e.target.value);
console.log(e.key);
if (e.key === "Enter") {
dict(e);
}
return false;
}
document.getElementById("input").addEventListener("input", ClearOutput());
function ClearOutput() {
document.querySelector(".def").innerHTML = "";
document.querySelector(".audio").innerHTML = "";
document.querySelector(".not__found").innerHTML = "";
}
async function getData(word) {
loading.style.display = "block";
const response = await fetch(
`https://www.dictionaryapi.com/api/v3/references/learners/json/${word}?key=${apiKey}`
);
const data = await response.json();
console.log(data);
if (!data.length) {
loading.style.display = "none";
notFound.innerText = " No result found";
return;
}
if (typeof data[0] === "string") {
loading.style.display = "none";
let heading = document.createElement("h3");
heading.innerText = "Did you mean?";
notFound.appendChild(heading);
data.forEach((element) => {
let suggetion = document.createElement("span");
suggetion.classList.add("suggested");
suggetion.innerText = element;
notFound.appendChild(suggetion);
});
return;
}
// Result found
loading.style.display = "none";
let defination = data[0].shortdef[0];
defBox.innerText = defination;
// Sound
const soundName = data[0].hwi.prs[0].sound.audio;
if (soundName) {
renderSound(soundName);
}
console.log(data);
}
function renderSound(soundName) {
// https://media.merriam-webster.com/soundc11
let subfolder = soundName.charAt(0);
let soundSrc = `https://media.merriam-webster.com/soundc11/${subfolder}/${soundName}.wav?key=${apiKey}`;
let aud = document.createElement("audio");
aud.src = soundSrc;
aud.controls = true;
audioBox.appendChild(aud);
}