-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
81 lines (67 loc) · 2.25 KB
/
app.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
let input = document.querySelector('#input');
let searchBtn = document.querySelector('#search');
let apiKey = 'API - KEY - HERE';
let notFound = document.querySelector('.not__found');
let defBox = document.querySelector('.def');
let audioBox = document.querySelector('.audio');
let loading = document.querySelector('.loading');
searchBtn.addEventListener('click', function(e){
e.preventDefault();
// Clear Old Data
audioBox.innerHTML = '';
notFound.innerText = '';
defBox.innerText = '';
// Get Input Data
let word = input.value;
// call API get data
if (word === '') {
alert('Please Enter A Word ..');
return;
}
getData(word);
})
async function getData(word) {
loading.style.display = 'block';
// Ajax Call
const response = await fetch(`https://www.dictionaryapi.com/api/v3/references/learners/json/${word}?key=${apiKey}`);
const data = await response.json();
// if empty result
if (!data.length) {
loading.style.display = 'none';
notFound.innerText = ' No result found';
return;
}
// If result is suggetions
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 (Demo)
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);
}