-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
99 lines (99 loc) · 3 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const search = document.getElementById("search"),
submit = document.getElementById("submit"),
random = document.getElementById("random"),
mealsEl = document.getElementById("meals"),
resultHeading = document.getElementById("result-heading"),
single_mealEl = document.getElementById("single-meal");
function searchMeal(e) {
e.preventDefault();
single_mealEl.innerHTML = "";
const term = search.value;
console.log(term);
if (term.trim()) {
fetch(`https://www.themealdb.com/api/json/v1/1/search.php?s=${term}`)
.then((res) => res.json())
.then((data) => {
console.log(data);
resultHeading.innerHTML = `<h2>Search results for '${term}':</h2>`;
if (data.meals === null) {
resultHeading.innerHTML = `<p>There are no search results. Try again!</p>`;
} else {
mealsEl.innerHTML = data.meals
.map(
(meal) => `
<div class="meal">
<img src="${meal.strMealThumb}" alt="${meal.strMeal}"/>
<div class="meal-info" data-mealID="${meal.idMeal}">
<h3>${meal.strMeal}</h3></div>
</div>`
)
.join("");
}
});
search.value = "";
} else {
alert("Please enter a search term");
}
}
function getMealById(mealID) {
fetch(`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${mealID}`)
.then((res) => res.json())
.then((data) => {
const meal = data.meals[0];
addMealToDOM(meal);
});
}
function getRandomMeal() {
mealsEl.innerHTML = "";
resultHeading.innerHTML = "";
fetch(`https://www.themealdb.com/api/json/v1/1/random.php`)
.then((res) => res.json())
.then((data) => {
const meal = data.meals[0];
addMealToDOM(meal);
});
}
function addMealToDOM(meal) {
const ingredients = [];
for (let i = 1; i <= 20; i++) {
if (meal[`strIngredient${i}`]) {
ingredients.push(
`${meal[`strIngredient${i}`]}-${meal[`strMeasure${i}`]}`
);
} else {
break;
}
}
single_mealEl.innerHTML = `
<div class="single-meal">
<h1>${meal.strMeal}</h1>
<img src="${meal.strMealThumb}" alt="${meal.strMeal}"/>
<div class="single-meal-info">
${meal.strCategory ? `<p>${meal.strCategory}</p>` : ""}
${meal.strArea ? `<p>${meal.strArea}</p>` : ""}
</div>
<div class="main">
<p>${meal.strInstructions}</p>
<h2>Ingredients</h2>
<ul>
${ingredients.map((ing) => `<li>${ing}</li>`).join("")}
</ul>
</div>
</div>`;
}
submit.addEventListener("submit", searchMeal);
random.addEventListener("click", getRandomMeal);
mealsEl.addEventListener("click", (e) => {
const mealInfo = e.path.find((item) => {
if (item.classList) {
return item.classList.contains("meal-info");
}
else {
return false;
}
});
if (mealInfo) {
const mealID = mealInfo.getAttribute("data-mealid");
getMealById(mealID);
}
});