document.addEventListener('DOMContentLoaded', () => { const generateForm = document.querySelector(".generate-form"); const imageGallery = document.querySelector(".image-gallery"); let isImageGenerating = false; const updateImageCard = (imgDataArray) => { imgDataArray.forEach((imgObject, index) =>{ const imgCard = imageGallery.querySelectorAll(".img-card")[index]; const imgElement = imgCard.querySelector("img"); const downloadBtn = imgCard.querySelector(".download-btn"); // Set the image source to the AI-generated image data const aiGeneratedImg = `${imgObject}`; // console.log(aiGeneratedImg); imgElement.src = aiGeneratedImg; // When the image is loaded, remove the loading class and set download attributes imgElement.onload = () => { imgCard.classList.remove("loading"); } // Set the download button to open the image in a new tab downloadBtn.onclick = () => { window.open(aiGeneratedImg, '_blank'); // Open the image in a new tab }; }); } const generateAiImages = async (userPrompt, userImgQuantity) => { try{ const response = await fetch(`https://death-image.ashlynn.workers.dev/?prompt=${encodeURIComponent(userPrompt)}&image=${encodeURIComponent(userImgQuantity)}&dimensions=tall&safety=false`); if (!response.ok) throw new Error(`Failed to generate images! Please try again. ${response.status}`); const data = await response.json(); // Get data from response // console.log(data) // Get the images array from the response const images = data.images; // console.log(images) updateImageCard([...images]); } catch (error){ alert(error.message); } finally{ isImageGenerating = false; } } const handleFormSubmission = (e) => { e.preventDefault(); if(isImageGenerating) return; isImageGenerating = true; // Get user input and image quantity values const userPrompt = e.srcElement[0].value; const userImgQuantity = e.srcElement[1].value; // Creating HTML markup for image cards with loading state const imgCardMarkup = Array.from({length: userImgQuantity}, () => `
` ).join(""); imageGallery.innerHTML = imgCardMarkup; generateAiImages(userPrompt, userImgQuantity); // console.log(imgCardMarkup); } generateForm.addEventListener("submit", handleFormSubmission); });