|  | 
|  | 1 | +const searchMeal = async (e) => { | 
|  | 2 | +  e.preventDefault(); | 
|  | 3 | + | 
|  | 4 | +  // Select Elements | 
|  | 5 | +  const input = document.querySelector(".input"); | 
|  | 6 | +  const title = document.querySelector(".title"); | 
|  | 7 | +  const info = document.querySelector(".info"); | 
|  | 8 | +  const img = document.querySelector(".img"); | 
|  | 9 | +  const ingredientsOutput = document.querySelector(".ingredients"); | 
|  | 10 | + | 
|  | 11 | +  const showMealInfo = (meal) => { | 
|  | 12 | +    const { strMeal, strMealThumb, strInstructions } = meal; | 
|  | 13 | +    title.textContent = strMeal; | 
|  | 14 | +    img.style.backgroundImage = `url(${strMealThumb})`; | 
|  | 15 | +    info.textContent = strInstructions; | 
|  | 16 | + | 
|  | 17 | +    const ingredients = []; | 
|  | 18 | + | 
|  | 19 | +    for (let i = 1; i <= 20; i++) { | 
|  | 20 | +      if (meal[`strIngredient${i}`]) { | 
|  | 21 | +        ingredients.push( | 
|  | 22 | +          `${meal[`strIngredient${i}`]} - ${meal[`strMeasure${i}`]}` | 
|  | 23 | +        ); | 
|  | 24 | +      } else { | 
|  | 25 | +        break; | 
|  | 26 | +      } | 
|  | 27 | +    } | 
|  | 28 | + | 
|  | 29 | +    const html = ` | 
|  | 30 | +    <span>${ingredients | 
|  | 31 | +      .map((ing) => `<li class="ing">${ing}</li>`) | 
|  | 32 | +      .join("")}</span> | 
|  | 33 | +    `; | 
|  | 34 | + | 
|  | 35 | +    ingredientsOutput.innerHTML = html; | 
|  | 36 | +  }; | 
|  | 37 | + | 
|  | 38 | +  const showAlert = () => { | 
|  | 39 | +    alert("Meal not found :("); | 
|  | 40 | +  }; | 
|  | 41 | + | 
|  | 42 | +  // Fetch Data | 
|  | 43 | +  const fetchMealData = async (val) => { | 
|  | 44 | +    const res = await fetch( | 
|  | 45 | +      `https://www.themealdb.com/api/json/v1/1/search.php?s=${val}` | 
|  | 46 | +    ); | 
|  | 47 | + | 
|  | 48 | +    const { meals } = await res.json(); | 
|  | 49 | +    return meals; | 
|  | 50 | +  }; | 
|  | 51 | + | 
|  | 52 | +  // Get the user value | 
|  | 53 | +  const val = input.value.trim(); | 
|  | 54 | + | 
|  | 55 | +  if (val) { | 
|  | 56 | +    const meals = await fetchMealData(val); | 
|  | 57 | + | 
|  | 58 | +    if (!meals) { | 
|  | 59 | +      showAlert(); | 
|  | 60 | +      return; | 
|  | 61 | +    } | 
|  | 62 | + | 
|  | 63 | +    meals.forEach(showMealInfo); | 
|  | 64 | +  } else { | 
|  | 65 | +    alert("Please try searching for meal :)"); | 
|  | 66 | +  } | 
|  | 67 | +}; | 
|  | 68 | + | 
|  | 69 | +const form = document.querySelector("form"); | 
|  | 70 | +form.addEventListener("submit", searchMeal); | 
|  | 71 | + | 
|  | 72 | +const magnifier = document.querySelector(".magnifier"); | 
|  | 73 | +magnifier.addEventListener("click", searchMeal); | 
0 commit comments