|
| 1 | +const searchText = document.getElementById("search-input"); |
| 2 | +const searchBtn = document.getElementById("search-btn"); |
| 3 | +const imageCards = document.getElementById("image-cards"); |
| 4 | +const imageApi = "https://api.unsplash.com/search/photos?query="; |
| 5 | +const accessKey = "cZkBLec2VWlXBAgs785p7uw9nagFu_G0Zgb8e5lK400"; |
| 6 | +const fetchImages = async (query) => { |
| 7 | + if (!query) { |
| 8 | + console.log("Query is empty"); |
| 9 | + return; |
| 10 | + } |
| 11 | + try { |
| 12 | + const response = await fetch(`${imageApi}${query}&client_id=${accessKey}`); |
| 13 | + const data = await response.json(); |
| 14 | + console.log(data); |
| 15 | + |
| 16 | + displayImages(data.results); |
| 17 | + } catch (error) { |
| 18 | + console.log("Error fetching images:", error); |
| 19 | + } |
| 20 | +}; |
| 21 | + |
| 22 | +const displayImages = (images) => { |
| 23 | + imageCards.innerHTML = ""; |
| 24 | + images.forEach((image) => { |
| 25 | + const imageBlock = document.createElement("div"); |
| 26 | + const imgElement = document.createElement("img"); |
| 27 | + const imgCaption = document.createElement("p"); |
| 28 | + imgCaption.innerText = image.description; |
| 29 | + imgElement.src = image.urls.small; |
| 30 | + imgElement.alt = image.alt_description; |
| 31 | + imageBlock.className = "image-card"; |
| 32 | + imageBlock.appendChild(imgElement); |
| 33 | + imageBlock.appendChild(imgCaption); |
| 34 | + |
| 35 | + imageCards.appendChild(imageBlock); |
| 36 | + }); |
| 37 | +}; |
| 38 | + |
| 39 | +const searchImage = () => { |
| 40 | + const query = searchText.value.trim(); |
| 41 | + fetchImages(query); |
| 42 | +}; |
| 43 | + |
| 44 | +searchBtn.addEventListener("click", searchImage); |
0 commit comments