forked from Avdhesh-Varshney/blog-script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
276 lines (229 loc) · 8.97 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//logic for searching a random recipe by the selected search criteria
async function searchRandomRecipe() {
const apiUrl = `https://www.themealdb.com/api/json/v1/1/random.php`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Check if the API call was successful and contains meals
if (data.meals) {
searchByNameFromCard(data.meals[0].strMeal);
} else {
console.error('No recipes found for the specified category.');
}
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Added this function to handle the search based on the selected option
function performSearch() {
const searchBy = document.getElementById('searchBy').value;
switch (searchBy) {
case 'name':
searchByName();
break;
case 'categories':
searchByCategory();
break;
case 'cuisine':
searchByCuisine();
break;
case 'mainIngredient':
searchBymainIngredient();
break;
default:
console.error('Invalid search option');
break;
}
}
// Added this function to make an API call for a given name
async function searchRecipeByName(name) {
const apiUrl = `https://www.themealdb.com/api/json/v1/1/search.php?s=${name}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Check if the API call was successful and contains meals
if (data.meals) {
return data.meals;
} else {
return null; // No matching recipes found
}
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
}
// Added this function to handle the search by name
async function searchByName() {
const searchInput = document.getElementById('searchInput');
const searchTerm = searchInput.value.trim();
if (searchTerm !== '') {
// Split the search term into words
const searchWords = searchTerm.split(' ');
// Create an array to store the results
const results = [];
// Make API calls for each word
for (const word of searchWords) {
const recipes = await searchRecipeByName(word);
if (recipes) {
results.push(...recipes);
}
}
// Display the results
displayResults(results);
}
}
// Modify this function to display the results
function displayResults(results) {
const resultContainer = document.getElementById('resultContainer');
const relatedContainer = document.getElementById('relatedContainer');
resultContainer.innerHTML = ''; // Clear previous results
relatedContainer.innerHTML = ''; // Clear previous related results
document.getElementById('related-recipes').style.display = 'block';
if (results.length === 0) {
resultContainer.innerHTML = '<p>No matching recipes found.</p>';
return;
}
const searchInput = document.getElementById('searchInput');
const searchTerm = searchInput.value.trim().toLowerCase(); // Convert to lowercase for case-insensitive comparison
// Filter the results based on the user's search term
const filteredResults = results
.filter((recipe, index, self) => self.findIndex(r => r.strMeal.toLowerCase() === recipe.strMeal.toLowerCase()) === index)
.filter(recipe => recipe.strMeal.toLowerCase().includes(searchTerm));
// Display only the filtered results
filteredResults.forEach(recipe => {
const category = recipe.strCategory;
const cuisine = recipe.strArea;
const thumbnail = recipe.strMealThumb;
const recipeVideo = recipe.strYoutube;
const ingredients = getIngredientsList(recipe);
const instructions = recipe.strInstructions;
const resultHTML = `
<div class="recipe">
<img src="${thumbnail}" alt="${recipe.strMeal}">
<h2>${recipe.strMeal}</h2>
<p>Category: ${category}</p>
<p>Cuisine: ${cuisine}</p>
<p>Recipe Video: <a href="${recipeVideo}" target="_blank">Watch Here</a></p>
<h3>Ingredients:</h3>
<ul>${ingredients}</ul>
<h3>Procedure:</h3>
<p>${instructions}</p>
</div>
`;
resultContainer.innerHTML += resultHTML;
});
if (filteredResults.length === 0) {
resultContainer.innerHTML = '<p>No matching recipes found.</p>';
}
// Display all results in the related section (before filtering)
results.forEach(recipe => {
const category = recipe.strCategory;
const cuisine = recipe.strArea;
const thumbnail = recipe.strMealThumb;
const relatedCardHTML = `
<div class="related-card" onclick="searchByNameFromCard('${recipe.strMeal}')">
<img src="${thumbnail}" alt="${recipe.strMeal}">
<h4>${recipe.strMeal}</h4>
<p>Category: ${category}</p>
<p>Cuisine: ${cuisine}</p>
</div>
`;
relatedContainer.innerHTML += relatedCardHTML;
});
}
// Added this function to get the ingredients as an ordered list
function getIngredientsList(recipe) {
const ingredients = [];
for (let i = 1; i <= 30; i++) { // Assuming a maximum of 30 ingredients
const ingredient = recipe[`strIngredient${i}`];
const measure = recipe[`strMeasure${i}`];
if (ingredient && measure) {
ingredients.push(`<li>${measure} ${ingredient}</li>`);
} else {
break; // Stop when there are no more ingredients
}
}
return ingredients.join('');
}
// Added this function to search by category
async function searchByCategory() {
const searchInput = document.getElementById('searchInput');
const category = searchInput.value.trim();
const apiUrl = `https://www.themealdb.com/api/json/v1/1/filter.php?c=${category}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Check if the API call was successful and contains meals
if (data.meals) {
displayCategoryResults(data.meals, category);
} else {
console.error('No recipes found for the specified category.');
}
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Added this function to search by cuisine
async function searchByCuisine() {
const searchInput = document.getElementById('searchInput');
const category = searchInput.value.trim();
const apiUrl = `https://www.themealdb.com/api/json/v1/1/filter.php?a=${category}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Check if the API call was successful and contains meals
if (data.meals) {
displayCategoryResults(data.meals, category);
} else {
console.error('No recipes found for the specified category.');
}
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Added this function to search by main Ingredient
async function searchBymainIngredient() {
const searchInput = document.getElementById('searchInput');
const category = searchInput.value.trim();
const apiUrl = `https://www.themealdb.com/api/json/v1/1/filter.php?i=${category}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
// Check if the API call was successful and contains meals
if (data.meals) {
displayCategoryResults(data.meals, category);
} else {
console.error('No recipes found for the specified category.');
}
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Modify this function to display the category results
function displayCategoryResults(categoryResults, category) {
const resultContainer = document.getElementById('resultContainer');
const relatedContainer = document.getElementById('relatedContainer');
const relatedSection = document.querySelector('.related-recipes');
// Clear previous results and related recipes
resultContainer.innerHTML = '';
relatedContainer.innerHTML = '';
// Show the related recipes section
relatedSection.style.display = 'block';
// Display the category results as cards
categoryResults.forEach(recipe => {
const thumbnail = recipe.strMealThumb;
const name = recipe.strMeal;
const categoryCardHTML = `
<div class="category-card" onclick="searchByNameFromCard('${name}')">
<img src="${thumbnail}" alt="${name}">
<h3>${name}</h3>
</div>
`;
resultContainer.innerHTML += categoryCardHTML;
});
}
// Added this function to search by name when clicking a related recipe card
function searchByNameFromCard(name) {
searchInput.value = name;
searchByName();
}