-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (69 loc) · 2.38 KB
/
index.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
var searchbtn = document.querySelector('.searchbtn');
var searchbar = document.querySelector('.searchbar');
var recipecontainer = document.querySelector(".recipe-container");
var recipeDetailContent = document.querySelector(".recipe-detail-content")
var recipeClose = document.querySelector(".recipe-close-btn")
const fetchRecipe = async (query) =>{
recipecontainer.innerHTML="<h1>Searching recipes...<h1>"
try {
const data = await fetch(`https://www.themealdb.com/api/json/v1/1/search.php?s=${query}`
)
const response = await data.json();
recipecontainer.innerHTML=""
response.meals.forEach(meal => {
console.log(meal)
const recipeDiv = document.createElement('div');
recipeDiv.classList.add('recipe')
recipeDiv.innerHTML = `
<img src= "${meal.strMealThumb}">
<h3 class="name">${meal.strMeal}</h3>
<p class="dish-name">${meal.strArea} Dish</p>
<p class="category-name">category:${meal.strCategory}</p>
`
const button = document.createElement('button')
button.textContent = "View Recipe"
recipeDiv.appendChild(button)
// adding event listener to button
button.addEventListener('click',()=>{
openRecipe(meal);
})
recipecontainer.appendChild(recipeDiv)
});
} catch (error) {
recipecontainer.innerHTML="<h1>Recipe is not Available ...<h1>"
}
}
// function for fetching ingrediants
const fetchingIngredients =(meal) =>{
let ingredientslist = "";
for(let i=1; i<20; i++){
const ingredient = meal[`strIngredient${i}`];
if(ingredient){
const measure = meal[`strMeasure${i}`];
ingredientslist += `<li>${measure} ${ingredient}</li>`
}
else{
break
}
}
return ingredientslist;
}
const openRecipe =(meal) =>{
recipeDetailContent.innerHTML=`<h2 class="recipe-name">${meal.strMeal}</h2>
<h3>Ingredients:</h3>
<ul class ="list-ingredients">${fetchingIngredients(meal)}</ul>
<div>
<br> <h3>Instructions:</h3>
<p class="recipe-instruction" >${meal.strInstructions}</p>
</div>
`
recipeDetailContent.parentElement.style.display ="block"
}
recipeClose.addEventListener('click',()=>{
recipeDetailContent.parentElement.style.display ="none"
})
searchbtn.addEventListener('click', (e)=>{
e.preventDefault();
const searchInput = searchbar.value.trim();
fetchRecipe(searchInput);
})