Skip to content

Instantly share code, notes, and snippets.

@Ajinkgupta
Created January 9, 2024 10:54
Show Gist options
  • Save Ajinkgupta/3ab2916bb9a515ef82258dc5640ee427 to your computer and use it in GitHub Desktop.
Save Ajinkgupta/3ab2916bb9a515ef82258dc5640ee427 to your computer and use it in GitHub Desktop.
dictionaryapp.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dictionary App</title>
<!-- Include Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
<div class="max-w-md w-full p-6 bg-white rounded-md shadow-md">
<h1 class="text-2xl font-bold mb-4">Dictionary App</h1>
<div>
<label for="wordInput" class="block text-sm font-medium text-gray-600">Enter a word:</label>
<input type="text" id="wordInput" class="mt-1 p-2 w-full border rounded-md">
</div>
<button onclick="fetchDefinition()" class="mt-4 bg-blue-500 text-white p-2 rounded-md">Get Definition</button>
<div id="result" class="mt-8"></div>
</div>
<script>
async function fetchDefinition() {
const wordInput = document.getElementById('wordInput').value;
const apiUrl = `https://api.dictionaryapi.dev/api/v2/entries/en/${wordInput}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
displayDefinition(data);
} catch (error) {
displayError("Error fetching data. Please try again.");
}
}
function displayDefinition(data) {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = '';
data.forEach(entry => {
const entryDiv = document.createElement('div');
entryDiv.classList.add('mb-4');
// Display word and phonetic
entryDiv.innerHTML += `<h2 class="text-xl font-bold">${entry.word}</h2>`;
entryDiv.innerHTML += `<p class="text-gray-600 mb-2">Phonetic: ${entry.phonetic}</p>`;
// Display phonetics
if (entry.phonetics && entry.phonetics.length > 0) {
entryDiv.innerHTML += '<p class="mb-2">Phonetics:</p>';
entry.phonetics.forEach(phonetic => {
entryDiv.innerHTML += `<p class="ml-4">${phonetic.text}</p>`;
});
}
// Display meanings
entryDiv.innerHTML += '<p class="font-bold mt-2">Meanings:</p>';
entry.meanings.forEach(meaning => {
entryDiv.innerHTML += `<p class="ml-4"><span class="font-bold">${meaning.partOfSpeech}:</span> ${meaning.definitions[0].definition}</p>`;
entryDiv.innerHTML += `<p class="ml-8 text-gray-600">${meaning.definitions[0].example}</p>`;
});
resultDiv.appendChild(entryDiv);
});
}
function displayError(message) {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = `<p class="text-red-500">${message}</p>`;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment