-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeaning.js
67 lines (58 loc) · 2.27 KB
/
meaning.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
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('submit').addEventListener('click', function () {
const word = document.getElementById('word1').value.trim();
if (word !== '') {
fetchMeaning(word);
} else {
document.getElementById('meaningDisplay').innerHTML =
`<p style="color: red;">Please Enter a word to see its meaning</p>`;
}
});
document.getElementById('synonyms').addEventListener('click', function () {
const word = document.getElementById('word2').value.trim();
if (word !== '') {
fetchSynonym(word);
} else {
document.getElementById('synonymDisplay').innerHTML =
`<p style="color: red;">Please Enter a word to see its synonyms</p>`;
}
});
});
async function fetchMeaning(word) {
const res = await fetch(`https://api.api-ninjas.com/v1/dictionary?word=${word}`, {
method: "GET",
headers: {
'X-Api-Key': CONFIG.API_KEY
}
});
const record = await res.json();
const meanings = record.definition;
if (!meanings) {
document.getElementById('meaningDisplay').innerHTML =
`<p style="color: red;">No meaning found</p>`;
} else {
const parts = meanings.split(/\d+\./);
let formattedMeaning = "";
for (let i = 0; i < parts.length; i++) {
formattedMeaning += `<p><b>${i + 1}. </b>${parts[i].trim()}</p>`;
}
document.getElementById('meaningDisplay').innerHTML = formattedMeaning;
}
}
async function fetchSynonym(word) {
const res = await fetch(`https://api.api-ninjas.com/v1/thesaurus?word=${word}`, {
method: "GET",
headers: {
'X-Api-Key': CONFIG.API_KEY
}
});
const record = await res.json();
const synonyms = record.synonyms;
if (!synonyms || synonyms.length === 0) {
document.getElementById('synonymDisplay').innerHTML =
`<p style="color: red;">No synonyms found</p>`;
} else {
const firstFiveSynonyms = synonyms.slice(0, 5).join(", ");
document.getElementById('synonymDisplay').textContent = firstFiveSynonyms;
}
}