-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
294 lines (252 loc) · 11.6 KB
/
Copy pathapp.js
File metadata and controls
294 lines (252 loc) · 11.6 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
const wordInput = document.getElementById('word-input');
const searchBtn = document.getElementById('search-btn');
const navTitle = document.getElementById('nav-title')
const titleContainer = document.getElementById('title-container');
const meaningContainer = document.getElementById('meaning-container');
const title = document.getElementById('title');
const pronunciation = document.getElementById('pronunciation');
const meaning = document.getElementById('meaning');
const description = document.getElementById('description');
const synonyms = document.getElementById('synonyms');
const audioBtn = document.getElementById('audio-btn');
const audio = document.getElementById('audio');
const definitionsContainer = document.getElementById('definitions-container');
audioBtn.style.display = 'none';
// Messages
const msg = {
msg1: "Did you know? The word 'dictionary' comes from the Latin 'dictionarius', meaning a book of words ;)",
msg2: "Unlock the full power of words 🥸",
msg3: "Curious about a word? Type it in below and unlock its full potential!",
msg4: "More than just definitions, hear how words are pronounced and see them in action!"
};
const keys = Object.keys(msg); // Get the keys of th object
const messages = Object.values(msg); // Convert object to an array
// Select a random message, duplicates may occur
const randomKey = keys[Math.floor(Math.random() * keys.length)];
const randomMsg = msg[randomKey];
// Select a random message, no duplicates (better for user experience)
let displayedMsg = JSON.parse(localStorage.getItem('displayedMsg')) || []; // getItem returns the value of the key, if the key doesn't exist, it returns null
const getRandomMsg = () => {
const availableMsg = messages.filter((_, index) => !displayedMsg.includes(index));
// console.log(displayedMsg);
// console.log(availableMsg);
if (availableMsg.length === 0) {
// Reset if all messages have been displayed
displayedMsg = [];
localStorage.removeItem('displayedMsg');
return getRandomMsg();
}
const randomIndex = Math.floor(Math.random() * availableMsg.length);
const selectedMsg = availableMsg[randomIndex];
// Get the index of the selected message to uodate displayedMsg
const selectedIndex = messages.indexOf(selectedMsg);
displayedMsg.push(selectedIndex);
// Update localStorage
localStorage.setItem('displayedMsg', JSON.stringify(displayedMsg));
return selectedMsg;
};
const firstElement = document.createElement('p');
// firstElement.innerText = randomMsg;
firstElement.innerText = getRandomMsg();;
firstElement.classList.add('first-element');
definitionsContainer.appendChild(firstElement);
// Fetch API
async function fetchApi(word) {
try {
title.innerText = '';
pronunciation.innerText = '';
definitionsContainer.innerHTML = '';
audio.src = '';
audioBtn.style.display = 'none';
const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
const result = await fetch(url).then((res) => res.json());
if (result.title) {
title.innerText = `No results found for «${word}»`;
title.classList.add('not-found');
return;
}
// Title and pronunciation
title.innerText = result[0].word;
console.log(result[0].phonetics);
const phoneticsAudio = result[0].phonetics.find((phonetic) => phonetic.audio);
const phoneticsText = result[0].phonetics.find((phonetic) => phonetic.text);
console.log(phoneticsAudio);
console.log(phoneticsText);
if (phoneticsAudio) {
// Set pronunciation (if available)
pronunciation.innerText = phoneticsAudio.text || (phoneticsText ? phoneticsText.text : '');
pronunciation.style.display = 'inline-flex';
// Set audio (if available)
audio.src = phoneticsAudio.audio;
audioBtn.style.display = 'inline-flex';
} else if (phoneticsText) {
// No audio, only text
pronunciation.innerText = phoneticsText.text;
pronunciation.style.display = 'inline-flex';
} else {
pronunciation.style.display = 'none';
audioBtn.style.display = 'none';
}
// Also works, but less readable
// if (phoneticsAudio) {
// if (phoneticsAudio.text) {
// pronunciation.innerText = phoneticsAudio.text || '';
// pronunciation.style.display = 'inline-flex';
// }
// else {
// result[0].phonetics.forEach((phonetic) => {
// if (phonetic.text) {
// // pronunciation.innerText = phonetic.text[phonetic.text.length - 1] || '';
// pronunciation.innerText = phonetic.text || '';
// pronunciation.style.display = 'inline-flex';
// }
// });
// }
// audio.src = phoneticsAudio.audio;
// audioBtn.style.display = 'inline-flex';
// // console.log(pronunciation);
// // console.log(phonetics);
// } else {
// result[0].phonetics.forEach((phonetic) => {
// if (phonetic.text) {
// // pronunciation.innerText = phonetic.text[phonetic.text.length - 1] || '';
// pronunciation.innerText = phonetic.text || '';
// pronunciation.style.display = 'inline-flex';
// }
// });
// }
// console.log(phoneticsAudio);
// Meanings, partOfSpeech and definitions
result[0].meanings.forEach((meaning, meaningIndex) => {
const meaningElement = document.createElement('div');
meaningElement.classList.add('meaning');
// Part of speech
const partOfSpeech = document.createElement('span');
partOfSpeech.innerHTML = `<strong>${meaning.partOfSpeech}</strong>`;
meaningElement.appendChild(partOfSpeech);
// Definitions
meaning.definitions.forEach((definition, definitionIndex) => {
const definitionElement = document.createElement('p');
definitionElement.classList.add('meaning');
definitionElement.style.display = 'block';
let space = ' ';
definitionElement.innerText = `${meaningIndex + 1}.${definitionIndex + 1}. ${definition.definition}`;
meaningElement.appendChild(definitionElement);
// console.log(definition);
// Example (if available)
if (definition.example) {
const exampleElement = document.createElement('span');
exampleElement.classList.add('example');
exampleElement.innerText = `${definition.example}`;
meaningElement.appendChild(exampleElement);
}
});
// Synonyms (if available)
if (meaning.synonyms.length > 0) {
const synonymsElement = document.createElement('p');
synonymsElement.classList.add('synonyms');
synonymsElement.classList.add('meaning');
synonymsElement.innerHTML = `Syn.: <strong>${meaning.synonyms.join(', ')}</strong>`;
meaningElement.appendChild(synonymsElement);
}
meaningElement.style.paddingBottom = '2rem';
definitionsContainer.classList.add('meaning-container');
// definitionsContainer.classList.add('box');
definitionsContainer.appendChild(meaningElement);
});
} catch (error) {
console.log(error);
title.innerText = 'Something went wrong... Please try again later.'
}
}
// First try ;)
// async function fetchApi(word) {
// try {
// titleContainer.style.display = 'none';
// meaningContainer.style.display = 'none';
// const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
// const result = await fetch(url).then((res) => res.json());
// if(result.title) {
// meaningContainer.style.display = 'block';
// title.innerText = word;
// meaning.innerText = 'Meaning not found :/';
// audioBtn.style.display = 'none';
// } else {
// meaningContainer.style.display = 'block';
// audioBtn.style.display = 'inline-flex';
// title.innerText = result[0].word;
// pronunciation.innerText = result[0].phonetics[1].text;
// audioBtn.src = result[0].phonetics[1].audio;
// for(let i = 0; i < result[0].meanings.length; i++) {
// // meaning.innerText = `${i + 1} + ". " + result[0].meanings[i].definitions[0].definition`;
// // description.innerText = result[0].meanings[i].partOfSpeech;
// // if(result[0].meanings[i].synonyms.length > 0) {
// // synonyms.style.display = 'block';
// // synonyms.innerText = 'Syn.: ' + result[0].meanings[i].synonyms.join(', ');
// // }
// const meaning = result[0].meanings[i];
// const definitions = meaning.definitions;
// for(let j = 0; j < definitions.length; j++) {
// const definition = definitions[j];
// meaning.innerText += `${i + 1}.${j + 1}. ${definition.definition}`;
// description.innerText = `${meaning.partOfSpeech}`;
// if(meaning.synonyms.length > 0) {
// synonyms.style.display = 'block';
// synonyms.innerText = `Syn.: ${meaning.synonyms.join(', ')}`;
// }
// }
// }
// }
// } catch (error) {
// console.log(error);
// }
// }
wordInput.addEventListener('keyup', (e) => {
// if(e.target.value && wordInput.value.trim() != '' && e.key === 'Enter') {
// fetchApi(e.target.value);
// wordInput.value = '';
// wordInput.blur();
// }
if (e.key === 'Enter') {
const word = wordInput.value.trim();
if (word) {
fetchApi(word);
wordInput.value = '';
wordInput.blur();
} else {
title.innerText = 'Please enter a word';
}
}
});
navTitle.addEventListener('click', () => {
window.location.href = 'index.html';
navTitle.style.cursor = 'pointer';
});
// Search word by clicking on the definition
// definitionsContainer.addEventListener('click', (e) => {
// const clickedWord = e.target.innerText.trim();
// if(clickedWord && e.target.classList.contains('meaning')){
// fetchApi(clickedWord);
// }
// });
searchBtn.addEventListener('click', () => {
const word = wordInput.value.trim();
if (word) {
fetchApi(wordInput.value);
wordInput.value = '';
wordInput.blur();
} else {
title.innerText = 'Please enter a word';
// title.classList.add('not-found')
title.classList.add('first-element')
pronunciation.innerText = '';
definitionsContainer.innerHTML = '';
audio.src = '';
audioBtn.style.display = 'none';
}
});
audioBtn.addEventListener('click', () => {
if (audio.src) {
audio.play();
}
});