i am using unsplash api to show images.i want to download the image when user click on download icon.But i don't know how to add this functionality.here is what i did so far.In the below code i fetch the images from unsplash api and display them in imageContainer by using display grid ...
- here is my html*
<!-- image container -->
<div class="imageContainer grid mt-10 p-2"></div>
<!-- image popup container -->
<div class="container height content z-20">
<div class="icons">
<i class="fa-solid fa-arrow-down downloadIcon"></i>
<i class="fa-solid fa-xmark crossIcon"></i>
</div>
<div class="imgShowed imgfit z-20"></div>
</div>
- here is my js*
let imageContainer = document.querySelector(".imageContainer");
let imgShowed = document.querySelector(".imgShowed");
let container = document.querySelector(".container");
let crossIcon = document.querySelector(".crossIcon");
let downloadIcon = document.querySelector(".downloadIcon")
// function to fetch image
function getimage() {
imageContainer.innerHTML = "";
(url =
"https://api.unsplash.com/search/photos?query=" +
input.value +
"&per_page=1200&client_id=5OXcnxdQpZLtAG0_jRNpqEQhTlUOQL3TKviFAUbBKm8"),
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
data.results.forEach((element) => {
let Div = document.createElement("Div");
Div.setAttribute("class", "imgDiv");
Div.setAttribute("data-downloadurl", `${element.links.download}`);
let img = document.createElement("img");
img.src = `${element.urls.regular}`;
Div.appendChild(img);
document.querySelector(".imageContainer").appendChild(Div);
imagepopup()
});
});
}
document.getElementById("btn").addEventListener("click", getimage);
// image popup function
function imagepopup(){
let imgDiv = document.querySelectorAll(".imgDiv");
imgDiv.forEach(element => {
element.addEventListener("click",(e)=>{
container.style.display="block"
let target = e.currentTarget
let clickedimagesrc = target.firstChild.src
imgShowed.innerHTML=`<img src="${clickedimagesrc}" class="imgfit" alt="...">`
downloadIcon.addEventListener("click",()=>{
let url=target.dataset.downloadurl
downloadIMG(url)
})
})
});
}
function downloadIMG(){
const link = document.createElement('a');
link.style.display = 'none';
link.href = URL.createObjectURL(url);
link.download = file.name;
link.click();
}