-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
92 lines (78 loc) · 2.84 KB
/
script.js
File metadata and controls
92 lines (78 loc) · 2.84 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
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
91
92
let audioAvailable = true;
let definitionAvailable = true;
let audioElement = document.querySelector(".container").lastChild.previousSibling;
let customAudio = document.createElement("audio");
let customAudioSource = document.createElement("source");
customAudioSource.src = "./assets/awkward-silence-crickets-chirping-meme.mp3";
customAudioSource.type = "audio/mp3";
customAudio.setAttribute('controls', '');
customAudio.appendChild(customAudioSource);
document.querySelector("#search-bar").addEventListener('keydown', (event) => {
let word = document.getElementById("search-bar").value
if(event.key === 'Enter') {
LoadingText(word);
getAudioAndDefinition(word);
}
});
async function getAudioAndDefinition(searchWord) {
try{
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${searchWord}`);
const data = await response.json();
if(!data[0].meanings[0].definitions[0].definition) definitionAvailable = false;
const newAudioElement = document.createElement("audio");
newAudioElement.setAttribute('controls', '');
const audioSourceElement = document.createElement("source");
if(data[0].phonetics[0].audio) {
audioSourceElement.src = `${data[0].phonetics[0].audio}`;
audioAvailable = true;
}
else audioAvailable = false;
audioSourceElement.type = `audio/mp3`;
if(audioAvailable) {
newAudioElement.appendChild(audioSourceElement);
removeAudio(audioElement);
displayAudio(newAudioElement);
audioElement = newAudioElement;
}
else {
removeAudio(audioElement);
displayAudio(customAudio);
audioElement = customAudio;
}
if(definitionAvailable) {
displayDefinition(data[0].meanings[0].definitions[0].definition);
}
} catch(error) {
console.log(error);
}
}
function LoadingText(queryWord) {
document.querySelector(".state").innerHTML = `searching for the word <q>${queryWord}</q>`;
}
async function displayAudio(newAudio) {
try {
const promise1 = new Promise((resolve) => {
setTimeout(() => {
resolve(newAudio);
}, 1000);
});
document.querySelector(".container").appendChild(await promise1);
} catch(error) {
console.log(error);
}
}
function removeAudio(oldAudio) {
document.querySelector(".container").removeChild(oldAudio);
}
async function displayDefinition(definition) {
try {
const promise2 = new Promise((resolve) => {
setTimeout(() => {
resolve(definition);
}, 1000);
});
document.querySelector(".state").innerHTML = `${await promise2}`;
} catch(error) {
console.log(error);
}
}