Friday, September 10, 2021

Learn To Build a Simple Dictionary Application Using JavaScript - MakeUseOf - Dictionary

JavaScript is one of the most popular programming languages among web developers. While learning JavaScript, everyone begins with the basics and building simple applications using DOM manipulation.

In this article, you will learn how you can build a dictionary using JavaScript and DOM manipulation. This article expects you to know the basics of JavaScript before reading.

Having a Look at the API

API stands for Application Programming Interface. APIs simplify software development and innovation by enabling applications to exchange data and functionality easily and securely.

This project uses dictionaryapi.dev API. This is a free API that provides multiple definitions, phonetics, and other grammatical terms related to words that you search.

The link to the API is as follows:

https://api.dictionaryapi.dev/api/v2/entries/en/word

Frontend Layout of the Project

The frontend layout of this project is built using HTML and TailwindCSS. You can import TailwindCSS in your HTML file using the CDN given below.

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />

The HTML page has an input and a button where the user can enter the word to be searched. There are three more divs to display the part of speech, multiple definitions, and audio that helps you pronounce the word correctly. By default, these three divs have a display property of none. When the data is fetched from the API the display property of these divs will be set to block.

 
<div class="bg-green-100 min-h-screen pt-10">
<h2 class="text-green-600 text-5xl pt-4 font-semibold text-center">
Dictionary
</h2>
<div class="flex justify-center p-8 items-center">
<input
type="text"
placeholder="Enter the word"
id="word"
class="
py-2
w-1/4
focus:outline-none
border-2 border-green-600
rounded
px-3
"
/>
<button
id="search"
class="bg-green-600 text-white text-xl px-4 py-2 rounded">
Search
</button>
</div>
<div class="flex flex-col justify-center items-center">
<div id="partOfSpeechDiv" class="hidden">
<h2 class="text-xl text-gray-500 py-2" id="partOfSpeechHeader"></h2>
<p class="text-md" id="partOfSpeechPara"></p>
</div>
<div class="hidden" id="meaningDiv">
<h2 class="text-4xl py-3 px-3 text-green-500" id="meaningHeader"></h2>
</div>
<div id="audio" class="hidden"></div>
</div>
</div>
<script src="./index.js"></script>

This frontend will look like this

Front end layout of the dictionary project

Adding Functionality Using JavaScript

Before fetching the data through API and displaying it, you need to get access to HTML elements using their ids. You can get access to the ids using the JavaScript method getElementById().

const word = document.getElementById("word");
const search = document.getElementById("search");
const display = document.getElementById("display");
const partOfSpeechDiv = document.getElementById("partOfSpeechDiv");
const partOfSpeechHeader = document.getElementById("partOfSpeechHeader");
const partOfSpeechPara = document.getElementById("partOfSpeechPara");
const meaningDiv = document.getElementById("meaningDiv");
const audioDiv = document.getElementById("audio");
const meaningHeader = document.getElementById("meaningHeader");

Adding the Event Listener

The input element in the HTML page has an id named word. After getting access to the input element, you can retrieve the value of the text in the input element using the .value attribute.

The search button has the id named search. You have to add a click event listener to trigger the event and make a function call to fetch the data through API.

Async and Await

Since 2017, JavaScript has introduced the concept of async and await to perform asynchronous requests. You use async-await instead of .then and .catch to resolve and reject promises.

Related: Synchronous vs. Asynchronous Programming: How Are They Different?

search.addEventListener("click", async () => {
try {
let url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word.value.toLowerCase()}`;
const res = await fetch(url);
const data = await res.json();
displayData(data);
} catch (error) {
console.log(error);
}
});

To work with promises using async-await, you need to add the async keyword before the function definition. And whenever you make a request or call a function, you have to add the await keyword before it.

The await keyword pauses the further execution of the function until the previous request does not get completed.

You need to perform the entire async-await promise action in the try-catch block. If the promise is not able to fetch the data then it will display the error in the catch block. Before passing the word to the API, it should be in the lowercase format for accurate results. You can use the .lowercase() string method to convert the word.

The fetch method shall retrieve the data from the API. You have to add the await keyword so that the function pauses at that moment while the fetch method is retrieving the data.

After retrieving the data, you need to convert it in JSON format using the .json() method on the response.

Displaying the Data on the Web Page

After retrieving the data and converting it to JSON format, you have to display it on the web page. You need to call the displayData() method and pass the data to it.

The structure of the API response is as follows:

Image shows response of the data fetched from the API

The API returns the part of speech, multiple definitions, and phonetics of the words in the response.

You can get all the definitions of the given word using:

const meanings = data[0].meanings[0].definitions;

The variable meanings is an array that contains all the definitions of the given word.

To get the Part of Speech of the given word:

const partOfSpeech = data[0].meanings[0].partOfSpeech;

You can add the Part of Speech of the word using the .innerHTML attribute. In the HTML code, the part of speech div had the property of display none by default but, in the JavaScript code, after fetching the data, you need to set the display property to block.

Displaying the Definitions

You have to create a variable named meaningList. After appending all the definitions to this variable, you need to assign it the .innerHTML attribute to display it on the web page.

Related: The HTML Essentials Cheat Sheet: Tags, Attributes, and More

Loop through the meanings array and keep track of a single definition and the index at which it is present. Append the single definition and index to the meaningList variable inside the paragraph element of HTML.

Once you're out of the loop, you have to pass it to the .innerHTML attribute of meaningDiv.

Display the Audio Element on the Web Page

The response received by the API contains phonetics that help users to understand the pronunciation of the word. To add this sound on the web page, you need to create an audio element and pass phonetics in the src attribute of that element. Finally, you need to put the audio element in the audioDiv using the .innerHTML attribute.

Shows the definitions, part of speech and phonetics of the given word
const displayData = (data) => {
console.log(data);
const partOfSpeech = data[0].meanings[0].partOfSpeech;
const meanings = data[0].meanings[0].definitions;
partOfSpeechDiv.className =
"bg-gray-100 px-2 py-3 flex flex-col w-1/4 justify-center items-center border-2 border-green-500 rounded block";
partOfSpeechHeader.innerHTML = "Part of Speech";
partOfSpeechPara.innerHTML = partOfSpeech;
let meaningList = ``;
meanings.forEach((meaning, ind) => {
meaningList += `<p class='my-3 px-4 py-1 text-md'>${ind + 1}) ${
meaning.definition
} </p>`;
});
meaningDiv.className =
"text-center w-1/4 bg-gray-100 my-6 border-2 border-green-500 rounded block";
meaningHeader.innerText = "Meanings";
meaningDiv.innerHTML = meaningList;
let aud = `<audio src="${data[0].phonetics[0].audio}" controls>`;
audioDiv.className = "block";
audioDiv.innerHTML = aud;
};
Shows the definitions, part of speech and phonetics for the word book

Add Another Project to Your List

Now that you have learned to build a dictionary app using JavaScript, it's time for you to build some exciting projects by yourself. Building projects will not only brush up on your basics but also add projects to your resume.

Looking for more practice on JavaScript and DOM manipulation concepts? Here's another project that you can build to strengthen your skills.

build a todo list featured
How to Build a Basic To-Do List App Using JavaScript

One of the better project ideas for JavaScript beginners is to create a simple to-do list app. Here's our own tutorial for JS newbies.

About The Author

Adblock test (Why?)

No comments:

Post a Comment