forked from ZCW-Strahov/WhatisTypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
58 lines (48 loc) · 2.13 KB
/
index.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
//import './style.css';
document.addEventListener('DOMContentLoaded', function() {
const form = document.querySelector('#defineform');
const resultsContainer = document.getElementById('results-container');
if (!form || !resultsContainer) {
console.error("Form or results container not found in the DOM.");
return;
}
form.addEventListener('submit', async function(event) {
event.preventDefault();
const wordInput = form.querySelector('input[name="defineword"]');
const word = wordInput.value.trim();
if (!word) {
resultsContainer.innerHTML = `<p>Please enter a word to define.</p>`;
return;
}
resultsContainer.innerHTML = `<p>Loading...</p>`;
try {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
if (!response.ok) {
throw new Error(`No definition found for "${word}"`);
}
const data = await response.json();
displayDefinitions(data);
} catch (error) {
console.error('Error fetching the definition:', error);
resultsContainer.innerHTML = `<p>An error occurred while fetching the definition. Please try again later.</p>`;
}
});
function displayDefinitions(definitions) {
if (!definitions.length) {
resultsContainer.innerHTML = `<p>No definitions found.</p>`;
return;
}
resultsContainer.innerHTML = '';
definitions.forEach((definition) => {
const phoneticsHtml = definition.phonetics.map(p =>
`<span>${p.text} ${p.audio ? `<a href="https:${p.audio}" target="_blank"></a>` : ''}</span>`
).join(', ');
const meaningsHtml = definition.meanings.map(meaning =>
`<div><h4>${meaning.partOfSpeech}</h4><ul>` +
meaning.definitions.map(def => `<li>${def.definition}</li>`).join('') +
`</ul></div>`
).join('');
resultsContainer.innerHTML += `<h3>${definition.word} ${phoneticsHtml}</h3>${meaningsHtml}`;
});
}
});