Skip to content

Instantly share code, notes, and snippets.

@szemate
Last active November 9, 2021 13:03
Show Gist options
  • Save szemate/38288116e0eeef96bdc5f694d6de8e30 to your computer and use it in GitHub Desktop.
Save szemate/38288116e0eeef96bdc5f694d6de8e30 to your computer and use it in GitHub Desktop.
Fetch exercise

Fetch exercise

Create a dictionary page that shows word definitions from the Free Dictionary API. The API documentation can be found at https://dictionaryapi.dev/.

  1. Open the developer tools in your browser and try the API with different words. Figure out how to get a definition from the returned JSON object.
  2. Check what the response is when no definition is found.
  3. Copy-paste index.html and script.js below into VSCode and open index.html with live server.
  4. Complete script.js to show the first definition of the word from the input field when the user clicks the submit button. Don't forget to handle the case when no definition is found.
  5. Stretch goal: include all definitions of the word and the example sentences.

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />

    <title>Dictionary</title>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <h1>Dictionary</h1>
      </div>
      <div class="row mt-2">
        <form>
          <div class="input-group">
            <input type="text" class="form-control" id="wordInput" />
            <button type="submit" class="btn btn-primary" id="submitButton">Look up</button>
          </div>
        </form>
      </div>
      <div class="row mt-4" id="definition">
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>

script.js

const apiEndpoint = "https://api.dictionaryapi.dev/api/v2/entries/en/";

const submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", event => {
    event.preventDefault();
    
    const wordInput = document.getElementById("wordInput");
    const definitionContainer = document.getElementById("definition");

    // Add your solution here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment