Exercise: Objects

As you learned in your freecodecamp.org lessons, Javascript objects store information through ‘name value’ pairs. In plain English, this simply means that information is retrieved from an object by asking for it by name. You should be pretty familiar with these concepts after going through the lessons so let’s go ahead and put that knowledge to use in yet another lesson.

To begin, download this file named objects.zip.  Once the file is unzipped, you  should see a file named beverage.html and a js folder with another file inside named beverage.js. You will also have a ‘beveragepics’ folder with five beverage options. Move everything to wherever you are doing your work for this class and open both files simultaneously with your code editor.

As you can see some of your work is already done: both files have content and are connected via a script tag in beverage.html. In addition:

  • beverage.html has a button that calls a (presently empty) function in beverage.js
  • beverage.js contains an object named ‘drinkMenu’ that attaches a description to each drink option.
  • In addition to drinkMenu, beverage.js also contains an array with all of beverage names.

Retrieve descriptions via text entry

Goal: Type a drink name into the text field, click the button, and display the drink description.

For our first exercise we are going to use the text field and button that already exists to pull quotes from drinkMenu and make them appear inside of the h2 tags in the html document (id of “#aboutme”). This can be accomplished by adding just two lines of code to the serveDrink function. I am going to offer general instructions and your job is to figure out the rest.

  1. Create a variable (call it sName ) inside of the serveDrink function. Use document.querySelector to set the value of sName to the value of the text field (which, as you can see in the html file, has an id of “#adrink”)
  2. Use document.querySelector again to set the innerHtml property of #aboutme (tied to the <h2> tags) to the appropriate value in drinkMenu.
  3. Finally, add a conditional (if, else) statement with that displays the drink if the input matches a drink in the drinkMenu object. If the user types anything else, they will receive an error message (example: “Lemonade isn’t a valid drink.”).
Need a hint? Check it out here:
function serveDrink() {
    // Step 1: Get the drink name from the input field
    let sName = document.querySelector('#adrink').value;

    // Step 2: Check if the drink is in the drinkMenu object
    if (drinkMenu.hasOwnProperty(sName)) {
        // Step 3: Show the drink description
        document.querySelector('#aboutme').innerHTML = drinkMenu[sName];
    } else {
        // Step 4: Error message for invalid entry
        document.querySelector('#aboutme').innerHTML = sName + " isn't a valid drink.";
    }
}

Test it out! Type “Latte,” click the button, and the description should appear. Type “Lemonade,” click the button, and the error message should appear.

Retrieve descriptions from a dropdown list.

Hopefully, you are impressed with your project so far, but wouldn’t it be even better if the drink options were part of a dropdown list? Luckily, you know Javascript and you have an array of those drink names just waiting to be put to use, with just a tiny bit of coding. So let’s do it!

  1. Either delete or comment out the button and textfield in the html file, and replace them with a select field.
    <!-- Instead of button and input: -->
    <h1>Select a Drink</h1>
    <select id="adrink" onchange="serveDrink()">
    </select>
  2. As you can see, you will set the id of the select field to “#aname” and use ‘onchange’ to call the same quote function that you used in the previous exercise.
  3. Return to beverage.js. Just after the drinkArray but OUTSIDE of the serveDrink function, create a variable named drinkList and set its value to #adrink (via querySelector of course).
    let drinkList = document.querySelector("#adrink");
  4. At the top of beverage.js, add a display map to provide cleaner label options. The display map looks like this:
    let drinkDisplayMap = {
        "Latte": "Latte",
        "IcedMatchaLatte": "Iced Matcha Latte",
        "ChaiTea": "Chai Tea",
        "BubbleTea": "Bubble Tea",
        "ThaiIcedTea": "Thai Iced Tea"
    };
  5. Finally, build a for loop to add the drink options to the dropdown menu. This for loop uses the internal key that you created in the drinkDisplayMap to display the user friendly version of the drink name.
    for (let key in drinkDisplayMap) {
    drinkList.innerHTML += `<option value="${key}">${drinkDisplayMap[key]}</option>`;
    }

The serveDrink() function stays the same! Now, it’s just pulling values from the dropdown drink menu.

Add pictures

It’s not a menu without photos! The goal for this part of the exercise is to automatically display the matching image of the drink once it is selected.

  1. Add a new div tag to your html document underneath the h2 tag where quotes appear and give it an id named image.
  2. In the serveDrink function, add a line to the conditional statement.
    The code will include a document.querySelector and innerHtml, to make the appropriate image appear in the #image div tag that you created in the previous step.
    • Make sure your img src is correct. Since you are using inner html, the file path will go from beverage.html to the beveragepics folder.
      • Take a look at the image names in the ‘beveragepics’ folder. What a helpful coincidence that they match they keys in drinkMenu. You know, the same keys that are referenced by aDrink when you select a drink from the dropdown list.
      • Finally, add a line to the else statement as well that displays no image if a drink is not selected.
Need a hint? Check it out:
function serveDrink() {
    let sName = document.querySelector('#adrink').value;

    if (drinkMenu.hasOwnProperty(sName)) {
        // Show description
        document.querySelector('#aboutme').innerHTML = drinkMenu[sName];

        // Show image
        document.querySelector('#image').innerHTML = 
            "<img src='beveragepics/" + sName + ".png' alt='" + drinkDisplayMap[sName] + "' style='max-width: 300px;'>";
    } else {
        document.querySelector('#aboutme').innerHTML = sName + " isn't a valid drink.";
        document.querySelector('#image').innerHTML = "";
    }
}

Need a challenge? Try these:

  • Add a “Clear” button
  • Add a “Random drink” button
  • Add a price with another object!