Set The Current Pizza

📝 We continue in the same project folder throughout this section.

What we will be doing

Objective

Make pizza names in the "working on" section clickable, then display the pizza name in the kitchen area's #current_pizza span.

Steps

  • In the createListOfPizzas() function, we create the pizza name using a <span> element. Add a class of pizza_name to this.
  • In the selectCurrentOrder() function, select all span elements with the class of pizza_name we just added.
  • Add an event listener to all these <span> elements, which should call a function called setCurrentPizza() when clicked.
  • Create the setCurrentPizza() function.
  • The HTML has a <span> in the kitchen area: <span id="current_pizza"></span>.
  • Set the selected pizza name to this element (hint- you can use the event data).
setting the current pizza image

You can try this our yourself, or, follow along below.

Adding the class to the pizza

To be able to click on these pizzas, first we will add a class to the pizza name element, this can be done when we create them in the createListOfPizzas function:

function createListOfPizzas(pizzas) {
  const pizzaList = document.createElement('ul');
  pizzas.forEach(function (pizza) {
    const quantity = buildElement('span', `${pizza.quantity} - `);
    const pizzaNameElement = buildElement('span', pizza.name);
    // 1. Add a class to each pizza:
    pizzaNameElement.classList.add('pizza_name');
    // ...

Selecting pizzas and adding event listeners

Then onto selectCurrentOrder() function to select the pizzas, and add the event listener:

function selectCurrentOrder(e) {
// 1. select pizzas with the class of pizza_name
const pizzas = document.querySelectorAll('.pizza_name');
// 2. add event listener, we use a loop since we can have multiple pizzas
pizzas.forEach(function (pizza) {
  pizza.addEventListener('click', setCurrentPizza);
});
// ...

Creating the setCurrentPizza function

The event listener calls a function called setCurrentPizza which we can now add at the bottom of the file:

function setCurrentPizza(e) {
  // 1. test everything works with a console log:
  console.log(e.target.innerText);

  // 2. save pizza name to variable
  const pizzaName = e.target.innerText;

  // 3. set pizza name to our HTML element:
  document.querySelector('#current_pizza').innerText = pizzaName;
}

Test this out and you can now click on the pizza names to move to the kitchen area. Next, we can use this selected element to display the steps to take inside of the method section.