Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- window.addEventListener('load', solve);
- async function solve() {
- const url = 'http://localhost:3030/jsonstore/cookbook/recipes';
- try {
- const response = await fetch(url);
- if (response.status !== 200) {
- console.error(response.status);
- return;
- }
- const data = await response.json();
- const main = document.querySelector('main');
- main.innerHTML = '';
- for (const recipeId in data) {
- const recipe = data[recipeId];
- const article = document.createElement('article');
- article.classList.add('preview');
- article.id = recipeId;
- const divTitle = document.createElement('div');
- divTitle.classList.add('title');
- divTitle.innerHTML = `<h2>${recipe.name}</h2>`;
- const divImage = document.createElement('div');
- divImage.classList.add('small');
- divImage.innerHTML = `<img src="${recipe.img}">`;
- article.appendChild(divTitle);
- article.appendChild(divImage);
- article.addEventListener('click', changeVisibility);
- main.appendChild(article);
- function changeVisibility() {
- const articleInfo = article.nextSibling;
- articleInfo.style.display = (articleInfo.style.display === 'block') ? 'none' : 'block';
- }
- const infoUrl = `http://localhost:3030/jsonstore/cookbook/details/${recipeId}`;
- const infoResponse = await fetch(infoUrl);
- if (infoResponse.status !== 200) {
- console.error(infoResponse.status);
- continue;
- }
- const infoData = await infoResponse.json();
- const articleInfo = createArticleInfo(infoData);
- main.insertBefore(articleInfo, article.nextSibling);
- }
- } catch (err) {
- console.error(err);
- }
- }
- function createArticleInfo(infoData) {
- const articleInfo = document.createElement('article');
- articleInfo.style.display = 'none';
- const h2El = document.createElement('h2');
- h2El.textContent = infoData.name;
- const divBand = document.createElement('div');
- divBand.classList.add('band');
- const divThumb = document.createElement('div');
- divThumb.classList.add('thumb');
- divThumb.innerHTML = `<img src="${infoData.img}">`;
- const divIngred = document.createElement('div');
- divIngred.classList.add('ingredients');
- divIngred.innerHTML = '<h3>Ingredients:</h3>';
- const divDescr = document.createElement('div');
- divDescr.classList.add('description');
- divDescr.innerHTML = '<h3>Preparation:</h3>';
- const ingrdUl = document.createElement('ul');
- infoData.ingredients.forEach(ingredient => {
- const liEl = document.createElement('li');
- liEl.textContent = ingredient;
- ingrdUl.appendChild(liEl);
- });
- infoData.steps.forEach(step => {
- const pEl = document.createElement('p');
- pEl.textContent = step;
- divDescr.appendChild(pEl);
- });
- articleInfo.appendChild(h2El);
- articleInfo.appendChild(divBand);
- divBand.appendChild(divThumb);
- divBand.appendChild(divIngred);
- divIngred.appendChild(ingrdUl);
- articleInfo.appendChild(divDescr);
- return articleInfo;
- }
Advertisement
Add Comment
Please, Sign In to add comment