Cocktail Recipe Generator

Suggested Cocktail Recipe:

'; return; } try { // Construct API query based on selected cocktail type and ingredients const queryIngredients = ingredientInput.map(item => item.trim()).join(','); let apiUrl = `${API_URL}filter.php?i=${queryIngredients}`; // If user selected a cocktail type, modify API query if (cocktailType !== 'Any') { apiUrl = `${API_URL}filter.php?c=${cocktailType}`; } // Fetch data from the API const response = await fetch(apiUrl); const data = await response.json(); // Handle no matching cocktail results if (!data.drinks || data.drinks.length === 0) { cocktailRecipeDiv.innerHTML = '

No cocktail recipes match the ingredients you entered.

'; return; } // Display the fetched recipes data.drinks.forEach(drink => { // Get detailed recipe information for each cocktail fetch(`${API_URL}lookup.php?i=${drink.idDrink}`) .then(response => response.json()) .then(detailData => { const cocktail = detailData.drinks[0]; const recipeDiv = document.createElement('div'); recipeDiv.classList.add('recipe-item'); recipeDiv.innerHTML = `

${cocktail.strDrink}

Ingredients: ${getIngredients(cocktail).join(", ")}

Instructions: ${cocktail.strInstructions}

`; cocktailRecipeDiv.appendChild(recipeDiv); }) .catch(error => console.error('Error fetching cocktail details:', error)); }); } catch (error) { cocktailRecipeDiv.innerHTML = '

Error fetching cocktail data. Please try again later.

'; } } // Function to extract ingredients from the cocktail object function getIngredients(cocktail) { const ingredients = []; for (let i = 1; i <= 15; i++) { if (cocktail[`strIngredient${i}`]) { ingredients.push(cocktail[`strIngredient${i}`]); } } return ingredients; } // Add event listener to the "Generate Recipe" button document.getElementById('generateRecipe').addEventListener('click', generateCocktailRecipe);
Scroll to Top