-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
96 lines (85 loc) · 2.71 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
let filteredRecipes;
const BASE_URL = "https://www.themealdb.com/api/json/v1/1/";
const input = document.querySelector("[data-input]");
const body = document.querySelector("body");
input.addEventListener("keyup", e => {
if(e.key === "Enter")
{
input.blur();
fetchRecipesByArea(input.value);
}
})
document.querySelector(".modal-close-button").addEventListener("click", ()=>{
document.querySelector("body").classList.remove("show-modal");
});
document.querySelector(".overlay").addEventListener("click", ()=>{
document.querySelector("body").classList.remove("show-modal");
});
async function fetchRecipesByArea(area) {
try {
body.classList.add("loading");
const response = await fetch(`${BASE_URL}filter.php?a=${area}`);
if(!response.ok) throw Error(response.status);
({meals : filteredRecipes} = await response.json());
if(filteredRecipes == null) throw Error(`No ${area} meals found!`);
console.log(filteredRecipes);
body.classList.remove("loading");
showImages();
}
catch (err) {
showModal("Error", err, "red");
body.classList.remove("loading");
}
}
function showImages() {
const imagesArea = document.querySelector(".images-area");
clearElement(imagesArea);
filteredRecipes.forEach(meal => {
const image = document.createElement("img");
image.src = meal.strMealThumb;
image.title = `${meal.strMeal}
Click to see recipe`;
image.classList.add("meal-image");
image.id = meal.idMeal;
image.addEventListener("click", showIngredients);
imagesArea.append(image);
});
}
function clearElement(elem) {
while(elem.firstChild)
elem.firstChild.remove();
}
async function showIngredients(e) {
try {
body.classList.add("loading");
const response = await fetch(`${BASE_URL}lookup.php?i=${e.target.id}`);
if(!response.ok) throw Error(response.status);
const {meals : [meal]} = await response.json();
console.log(meal);
const ingredients = [];
for(let i = 1; i <= 20; i++)
{
if(meal[`strIngredient${i}`] == "")
break;
ingredients.push(meal[`strMeasure${i}`] + " " + meal[`strIngredient${i}`]);
}
const content = `Ingredients:
${ingredients.join(`
`)}
Instructions:
${meal.strInstructions}`;
body.classList.remove("loading");
showModal(meal.strMeal, content);
}
catch (err) {
showModal("Error", err, "red");
body.classList.remove("loading");
}
}
function showModal(title, content, color = "green") {
document.querySelector(".modal-title").innerText = title;
document.querySelector(".modal-content").innerText = content;
document.querySelector(".modal-content").scrollTop = 0;
document.querySelector(".modal-header").style.backgroundColor = color;
body.classList.add("show-modal");
}