|
| 1 | +// Initialising global variables |
| 2 | +const get_meal_btn = document.getElementById('get_meal'); |
| 3 | +const meal_container = document.getElementById('meal'); |
| 4 | + |
| 5 | +get_meal_btn.addEventListener('click', () => { |
| 6 | + fetch('https://www.themealdb.com/api/json/v1/1/random.php') |
| 7 | + .then(res => res.json()) |
| 8 | + .then(res => { |
| 9 | + createMeal(res.meals[0]); |
| 10 | + }); |
| 11 | +}); |
| 12 | + |
| 13 | +const createMeal = (meal) => { |
| 14 | + const ingredients = []; |
| 15 | + // Get all ingredients from the object. Up to 20 |
| 16 | + for (let i = 1; i <= 20; i++) { |
| 17 | + if (meal[`strIngredient${i}`]) { |
| 18 | + ingredients.push(`${meal[`strIngredient${i}`]} - ${meal[`strMeasure${i}`]}`) |
| 19 | + } else { |
| 20 | + // Stop if no more ingredients |
| 21 | + break; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + const newInnerHTML = ` |
| 26 | + <div class="row1"> |
| 27 | + <div class="columns five"> |
| 28 | + <img src="${meal.strMealThumb}" alt="Meal Image"> |
| 29 | + ${meal.strCategory ? `<p><strong>Category:</strong> ${meal.strCategory}</p>` : ''} |
| 30 | + ${meal.strArea ? `<p><strong>Area:</strong> ${meal.strArea}</p>` : ''} |
| 31 | + ${meal.strTags ? `<p><strong>Tags:</strong> ${meal.strTags.split(',').join(', ')}</p>` : ''} |
| 32 | + <h5>Ingredients:</h5> |
| 33 | + <ul> |
| 34 | + ${ingredients.map(ingredient => `<li>${ingredient}</li>`).join('')} |
| 35 | + </ul> |
| 36 | + </div> |
| 37 | + <hr> |
| 38 | + <div class="columns seven"> |
| 39 | + <h4>${meal.strMeal}</h4> |
| 40 | + <p>${meal.strInstructions}</p> |
| 41 | + </div> |
| 42 | + </div> |
| 43 | + <hr> |
| 44 | + ${meal.strYoutube ? ` |
| 45 | + <div class="row2"> |
| 46 | + <h1>Video Recipe</h1> |
| 47 | + <div class="videoWrapper"> |
| 48 | + <iframe width="420" height="315" |
| 49 | + src="https://www.youtube.com/embed/${meal.strYoutube.slice(-11)}"> |
| 50 | + </iframe> |
| 51 | + </div> |
| 52 | + </div>` : ''} |
| 53 | + `; |
| 54 | + |
| 55 | + meal_container.innerHTML = newInnerHTML; |
| 56 | +} |
0 commit comments