Introduction
The fetch()api allows us to make HTTPS requests from the server to the browser.
We create a simple application that generates random cocktail inspirations to the users using theCocktailsDB API
Used Fetch API to get a list of cocktails from the Cocktails DB api Getting:
Cocktail image, Cocktail name, Cocktail glass,cocktail ingredients and measures
JavaScript concepts used
DOM manipulation
fetch() API
Event listeners
Create an empty folder where you will store the project.
The folder should have an index.js file , an index.html file and a style.css for custom styling
We start by making a fetch request to the CocktailsDB API URL.
fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
.then(res => res.json())
.then(res => {
createCocktail(res.drinks[0]);
});
});
After sending a fetch request to the API we get the list of the random cocktails, their images,ingredients, measure and recipe instructions and we update it on the DOM.
const createCocktail = (cocktail) => {
const ingredients = [];
// Get all ingredients from the object. Up to 20
for(let i=1; i<=20; i++) {
if(cocktail[`strIngredient${i}`]) {
ingredients.push(`${cocktail[`strIngredient${i}`]} - ${cocktail[`strMeasure${i}`]}`)
} else {
// Stop if no more ingredients
break;
}
}
const newInnerHTML = `
<div id="rowa" id="cocktail-dataa">
<div id="five">
<img src="${cocktail.strDrinkThumb}" >
</div>
<div id="seven">
<h4>${cocktail.strDrink}</h4>
<div class="likes">
<button id="likeButton">
<i class="fa fa-thumbs-up"></i>
</button>
<input type="number" id="inputLike" value="0" name="">likes</input>
</div>
<p><strong>Category:</strong> ${cocktail.strCategory}</p>
<p><strong>Glass type:</strong> ${cocktail.strGlass}</p>
<p><strong>Type:</strong> ${cocktail.strAlcoholic}</p>
<h5>Ingredients:</h5>
<ul>
${ingredients.map(ingredient => `<li>${ingredient}</li>`).join('')}
</ul>
<h5>Instructions:</h5>
<p>${cocktail.strInstructions}</p>
</div>
</div>
`;
You can go ahead and click on the getcocktail button to display a random cocktail on the screen.
Also, we use the click event listener to allow the user to add likes to the cocktails they like most
cocktail_container.innerHTML = newInnerHTML;
let likebtn = document.querySelector('#likeButton');
let inputLike= document.querySelector('#inputLike');
likebtn.addEventListener('click', () => {
inputLike.value = parseInt(inputLike.value) + 1;
// inputLike.style.color = "#12ff00";
})
Top comments (0)