-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
56 lines (50 loc) · 1.93 KB
/
Copy pathscript.js
File metadata and controls
56 lines (50 loc) · 1.93 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
53
54
55
56
const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";
const result = document.getElementById("result");
const sound = document.getElementById("sound");
const btn = document.getElementById("search-btn");
btn.addEventListener("click", () => {
let inpWord = document.getElementById("inp-word").value.trim();
if (!inpWord) return; // Avoid empty input
fetch(`${url}${inpWord}`)
.then(response => response.json())
.then(data => {
if (data.title === "No Definitions Found") {
result.innerHTML = `<h3 class="error">Couldn't Find The Word</h3>`;
return;
}
const phonetics = data[0].phonetics.find(p => p.audio); // Find a phonetic with audio
if (phonetics) {
sound.setAttribute("src", phonetics.audio);
} else {
sound.removeAttribute("src");
}
result.innerHTML = `
<div class="word">
<h3>${inpWord}</h3>
<button id="play-sound">
<i class="fas fa-volume-up"></i>
</button>
</div>
<div class="details">
<p>${data[0].meanings[0].partOfSpeech}</p>
<p>/${data[0].phonetic || ''}/</p>
</div>
<p class="word-meaning">
${data[0].meanings[0].definitions[0].definition}
</p>
<p class="word-example">
${data[0].meanings[0].definitions[0].example || ""}
</p>`;
document.getElementById("play-sound").addEventListener("click", playSound);
})
.catch(() => {
result.innerHTML = `<h3 class="error">Couldn't Find The Word</h3>`;
});
});
function playSound() {
if (sound.src) {
sound.play();
} else {
alert("No audio available for this word.");
}
}