Create Your Own Dictionary with HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create a dynamic dictionary using HTML, CSS, and JavaScript. Step-by-step guide to implement dictionaryapi for interactive word meanings.


Create Your Own Dictionary with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Welcome to our comprehensive guide on building a dynamic dictionary using the power of HTML, CSS, and JavaScript! In this tutorial, we'll walk you through the process of creating an interactive dictionary that fetches word definitions in real-time using the dictionaryapi. Whether you're a beginner or an experienced web developer, this guide will equip you with the skills to enhance user experience on your website. Let's dive in!

Why Build a Dynamic Dictionary?

Imagine having a dictionary on your website that not only provides definitions but also engages users with interactive features. A dynamic dictionary adds a new layer of user experience, making learning and exploring words more exciting. With the help of the dictionaryapi, we can access word meanings programmatically and display them dynamically on our web page.

Prerequisites

Before we get started, it's important to have a basic understanding of HTML, CSS, and JavaScript. Familiarity with these web technologies will make the process smoother. If you're new to these concepts, don't worry! We'll provide clear explanations and code examples to guide you through.

What is dictionaryapi?

The dictionaryapi is a powerful tool that allows developers to retrieve word definitions from various dictionaries programmatically. This means we can integrate it into our web application to provide users with instant access to word meanings without having to navigate away from our site.

By the end of this tutorial, you'll have a fully functional dynamic dictionary that you can proudly integrate into your website. So, are you ready to embark on this exciting journey of web development? Let's start by setting up the HTML structure in the next section!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our dictionary.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let me break down the different parts of the code for you:

1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being used.

2. <html lang="en">: The opening <html> tag defines the beginning of the HTML document. The lang attribute specifies that the content is in English.

3 <head>: The <head> section contains metadata about the document, such as character encoding, title, and links to external resources.

  • <meta charset="UTF-8">: Specifies the character encoding of the document to be UTF-8, which supports a wide range of characters.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: Provides compatibility settings for Internet Explorer.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the initial scale and width of the viewport for responsive design.
  • <title>Dictionary</title>: Sets the title of the web page to "Dictionary".
  • <link rel="stylesheet" href="styles.css">: Links to an external CSS file named "styles.css" for styling the page.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">: Links to the Font Awesome library for using icons.

4. <body>: The <body> section contains the visible content of the web page.

5. <audio id="sound"></audio>: Defines an empty audio element with an ID of "sound", likely to be used for playing audio.

6. <div class="container">: A container that wraps the main content of the page.

7. <header>Word Definition</header>: Displays the text "Word Definition" as a header.

8. <hr />: Inserts a horizontal line (a thematic break) for visual separation.

9. <div class="search">: A container for the search input and search-related elements.

  • <input type="text" placeholder="Search here..." required spellcheck="false">: An input field for entering search text. It's required and has spellcheck disabled.
  • <i class="fas fa-search"></i>: An icon from Font Awesome representing a search icon.
  • <span class="material-icons">close</span>: A span containing text or an icon (using a different icon library) for closing the search.

10. <p class="info-text"></p>: An empty paragraph that might be used to display informational text.

11. <ul>: An unordered list that contains list items.

  • <li class="word">: A list item representing a word and its details.
  • <div class="details">: A container for the word's details.
  • <p></p>: An empty paragraph likely used to display the word.
  • <span></span>: An empty span for additional details about the word.
  • <i class="fas fa-volume-up" class="volume" onclick="playSound()"></i>: An icon representing a volume-up icon, likely for playing audio. It has an onclick attribute to trigger a JavaScript function named "playSound()".

12. <div class="content">: A container for additional content (possibly related to the word's meaning).

  • <li class="meaning">: A list item representing the meaning of the word.
  • <div class="details">: A container for the meaning's details.
  • <p>Meaning</p>: A paragraph indicating that this is the meaning section.
  • <span></span>: An empty span likely intended for displaying the meaning.

13. <script src="script.js"></script>: Links to an external JavaScript file named "script.js" for scripting functionality.

This is the basic structure of our dictionary using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the dictionary is in place, the next step is to add styling to the dictionary using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our dictionary.

1. @import Rule: This rule is used to import an external CSS stylesheet from the specified URL. In this case, it's importing a Google Fonts stylesheet that provides the "Open Sans" font with different weights and styles for usage in the webpage.

2. * Selector Block: This rule sets some basic styling for all elements in the document, effectively resetting their default margin, padding, and box-sizing properties. It also applies anti-aliasing for better font rendering on webkit-based browsers.

3. body Selector Block: This rule sets styling for the <body> element. It makes the body a flex container with properties that center its child elements both horizontally and vertically.

4. ::selection Pseudo-element: This rule defines the styling for selected text on the page. When text is selected, it will have white text color and a blue background color.

5. .container Class: This rule defines the styling for elements with the class "container." It sets the width, border-radius, background, padding, and box-shadow properties to create a styled container for content.

6. .container header Selector Block: This rule styles the header within elements with the class "container." It sets the font size, font weight, and text alignment for the header text.

7. .container .search Selector Block: This rule styles a specific section within elements with the class "container." It defines relative positioning for its contents and adjusts the margin.

8. .search input Selector Block: This rule styles an <input> element within the .search section. It sets properties like height, width, font size, border-radius, padding, and border to style the input box.

9. .search input:focus Selector Block: This rule defines the appearance of the input element when it's in focus (clicked on). It adjusts padding and border properties to indicate focus.

10. .search input::placeholder Selector Block: This rule styles the placeholder text within the input element.

11. .search :where(i, span) Selector Block: This rule styles <i> and <span> elements within the .search section. It positions these elements absolutely within the .search section and applies styles like color and vertical alignment.

12. .search i Selector Block: This rule styles <i> elements within the .search section, positioning them to the left and adjusting pointer-events.

13. .search input:focus ~ i Selector Block: This rule styles the <i> element when the input is in focus, changing its color.

14. .search span Selector Block: This rule styles <span> elements within the .search section. It positions them to the right, adjusts the cursor, and controls their display.

15. .search input:valid ~ span Selector Block: This rule styles the <span> element when the input is valid (contains valid data), changing its display property.

16. .container .info-text Selector Block: This rule styles elements with the class .info-text, setting font size, color, and margin.

17. .container.active .info-text Selector Block: This rule hides the .info-text when its parent .container has the class active.

18. .info-text span Selector Block: This rule styles <span> elements within .info-text, setting the font weight.

19. .container ul Selector Block: This rule styles <ul> elements within .container, initially hiding them with zero height and opacity. It also applies transition effects.

20. .container.active ul Selector Block: This rule shows the <ul> element with class active, giving it opacity and height to reveal its content.

21. .container ul li Selector Block: This rule styles list items (<li>) within the <ul> element in the .container. It sets styles like display, margin, alignment, padding, and border to create a structured layout for each list item.

22. ul .word p Selector Block: This rule styles <p> elements within list items that have the class word. It sets font size and font weight to emphasize the primary word in the list item.

23. ul .word span Selector Block: This rule styles <span> elements within list items with class word, setting font size and color for secondary text.

24. ul .word i Selector Block: This rule styles <i> elements within list items with class word. It sets color, font size, and cursor properties, making it appear as a clickable element.

25. ul .content Selector Block: This rule styles the content within list items, setting a maximum height and enabling vertical scrolling when the content exceeds the specified height.

26. ul .content::-webkit-scrollbar Selector Block: This rule styles the scrollbar within the content area, setting its width to zero to hide it (for webkit-based browsers).

27. content li .details Selector Block: This rule styles the details section within list items, adding padding and a left border for a visual separation effect.

28. content li p Selector Block: This rule styles <p> elements within the content section of list items, setting font size and font weight.

29. content li span Selector Block: This rule styles <span> elements within the content section of list items, setting font size and color for secondary text.

30. @media screen and (max-width: 480px) Media Query: This media query applies styles when the screen width is at most 480 pixels. In this case, it adjusts the width of elements with the class .container to 350 pixels for better responsiveness on smaller screens.

This will give our dictionary an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url("https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@1,300;1,400;1,500&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  --webkit-font-smoothing: antialiased;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #efefef;
}
::selection {
  color: #fff;
  background: #4d59fb;
}
.container {
  width: 420px;
  border-radius: 7px;
  background: #fff;
  padding: 25px 28px 45px;
  box-shadow: 7px 7px 20px rgba(0, 0, 0, 0.05);
}
.container header {
  font-size: 28px;
  font-weight: 900;
  text-align: center;
}
.container .search {
  position: relative;
  margin: 35px 0 18px;
}
.search input {
  height: 53px;
  width: 100%;
  outline: none;
  font-size: 16px;
  border-radius: 5px;
  padding: 0 42px;
  border: 1px solid #999;
}
.search input:focus {
  padding: 0 41px;
  border: 2px solid #4d59fb;
}
.search input::placeholder {
  color: #b8b8b8;
}
.search :where(i, span) {
  position: absolute;
  top: 50%;
  color: #999;
  transform: translateY(-50%);
}
.search i {
  left: 18px;
  pointer-events: none;
  font-size: 16px;
}
.search input:focus ~ i {
  color: #4d59fb;
}
.search span {
  right: 15px;
  cursor: pointer;
  font-size: 18px;
  display: none;
}
.search input:valid ~ span {
  display: block;
}
.container .info-text {
  font-size: 13px;
  color: #9a9a9a;
  margin: -3px 0 -10px;
}
.container.active .info-text {
  display: none;
}
.info-text span {
  font-weight: 500;
}
.container ul {
  height: 0;
  opacity: 0;
  padding-right: 1px;
  overflow-y: hidden;
  transition: all 0.2s ease;
}
.container.active ul {
  opacity: 1;
  height: 130px;
}
.container ul li {
  display: flex;
  list-style: none;
  margin-bottom: 14px;
  align-items: center;
  padding-bottom: 17px;
  border-bottom: 1px solid #d9d9d9;
  justify-content: space-between;
}

ul .word p {
  font-size: 22px;
  font-weight: 500;
}
ul .word span {
  font-size: 12px;
  color: #989898;
}
ul .word i {
  color: #999;
  font-size: 15px;
  cursor: pointer;
}
ul .content {
  max-height: 215px;
  overflow-y: auto;
}
ul .content::-webkit-scrollbar {
  width: 0px;
}
.content li .details {
  padding-left: 10px;
  border-left: 3px solid #4d59fb;
}
.content li p {
  font-size: 17px;
  font-weight: 500;
}
.content li span {
  font-size: 15px;
  color: #7e7e7e;
}

@media screen and (max-width: 480px){
  .container{
    width: 350px;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Let's break down the code step by step:

1. The code starts by selecting various elements from the HTML document using the querySelector method. These elements include:

  • container: An element with the class "container" that serves as the main container for the app.
  • searchInput: An input element within the container, used for entering search queries.
  • sound: An HTML audio element with the id "sound," presumably for playing the pronunciation audio.
  • infoText: An element within the container to display information text (such as search results or messages).
  • removeIcon: A clickable element with the class "search" and a child "span," possibly used to clear the search input.

2. The audio variable is declared outside the functions to hold an instance of the Audio class. This will be used to play the pronunciation audio.

3. The data function is defined to handle the processing of API data and updating the UI with the word's details. It takes two parameters: result (the API response) and word (the searched word).

  • If the API response contains a title property, it means the word was not found, and an error message is displayed.
  • If the word is found in the API response, the UI is updated with the word's definition, part of speech, and pronunciation details.

4. The playSound function is defined to play the audio pronunciation using the play() method on the audio instance.

5. The search function is defined to initiate a search by calling the fetchApi function and passing the search word.

6. The fetchApi function is used to fetch word definitions and pronunciation from an external API. It makes a network request to the API using the provided word.

  • It removes the "active" class from the container to hide any previous search results.
  • It updates the infoText to show a loading message.
  • It constructs the API URL using the word parameter.
  • It uses the fetch API to make a GET request to the constructed URL.
  • The response is converted to JSON, and the data function is called to process the API response and update the UI.
  • If there's an error during the fetch, it displays an error message.

7. An event listener is added to the searchInput element for the "keyup" event. When a user types and releases a key, this event is triggered. If the pressed key is "Enter" and the input is not empty, the fetchApi function is called with the entered word.

8. Another event listener is added to the removeIcon element (possibly a clear button). When clicked, it clears the search input, focuses on the input, removes the "active" class from the container, and sets the color of infoText to gray.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const container = document.querySelector(".container"),
  searchInput = container.querySelector("input"),
  sound = document.getElementById("sound");
(infoText = container.querySelector(".info-text")),
  (removeIcon = container.querySelector(".search span"));
let audio;

function data(result, word) {
  if (result.title) {
    infoText.innerHTML = `Oops ;) we can't find <span>"${word}"</span>.`;
  } else {
    container.classList.add("active");
    let definitions = result[0].meanings[0].definitions[0];
    phontetics = `${result[0].meanings[0].partOfSpeech}  /${result[0].phonetics[0].text}/`;
    document.querySelector(".word p").innerText = result[0].word;
    document.querySelector(".word span").innerText = phontetics;
    document.querySelector(".meaning span").innerText = definitions.definition;
    audio = new Audio(result[0].phonetics[0].audio);
  }
}

function playSound() {
  audio.play();
}

function search(word) {
  fetchApi(word);
  searchInput.value = word;
}

function fetchApi(word) {
  container.classList.remove("active");
  infoText.innerHTML = `Searching :) `;
  let url = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;
  fetch(url)
    .then((response) => response.json())
    .then((result) => data(result, word))
    .catch(() => {
      infoText.innerHTML = `Oops ;) we can't find <span>"${word}"</span>.`;
    });
}

searchInput.addEventListener("keyup", (e) => {
  let word = e.target.value.replace(/\s+/g, " ");
  if (e.key == "Enter" && word) {
    fetchApi(word);
  }
});

removeIcon.addEventListener("click", () => {
  searchInput.value = "";
  searchInput.focus();
  container.classList.remove("active");
  infoText.style.color = "#9A9A9A";
});

Final Output:

Create Your Own Dictionary with HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, this journey of creating a dynamic dictionary using HTML, CSS, and JavaScript has equipped you with the skills to build an interactive and engaging platform for word exploration. By integrating the dictionaryapi, you've unlocked the potential to offer users real-time access to word meanings, enhancing their learning experience. From establishing the HTML structure to crafting captivating CSS styles, and finally infusing the magic of JavaScript, you've constructed a functional and user-friendly dictionary.

As you reflect on your accomplishments, remember that this dynamic dictionary is not just a standalone project but a stepping stone for future growth. User feedback will be invaluable for refining and enhancing the user experience. Embracing continuous learning in the ever-evolving landscape of web development will empower you to stay ahead of the curve. Moreover, considering advanced features and potential collaborations with language experts can further enrich the dictionary's value.

In this digital age, your dynamic dictionary stands as a testament to your creativity and technical acumen. It's not just a tool for word meanings, but a platform that fosters curiosity and learning. As you continue your journey in the world of web development, may this project be a source of inspiration for further innovation and meaningful contributions to the online community.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post