I have a gallery of pictures (dynamically fetched from a json). When I open the link, picture pops up, but I am not able to close it.
I would need either to add some kind of "Close button" or just to clear the code (onclick event?).
createImg.setAttribute("src", books[i].cover)
createImg.setAttribute("alt", "Avatar")
createImg.setAttribute("style", "width:290px;height:380px;")
var createButton = document.createElement("button");
createButton.setAttribute("type", "button");
createButton.setAttribute("id", books[i].detail);
createButton.addEventListener("click", function (event) {
var showPicture = document.getElementById("showPictureID")
// - clean code or close button (on click ??)
var createDet = document.createElement('img');
createDet.setAttribute("src", event.target.id)
createDet.setAttribute("alt", "image")
createDet.setAttribute("style", "position:fixed;top:20%;left:20%;")
var showPicture = document.getElementById("showPictureID")
showPicture.appendChild(createDet);
Not sure how to approach this. Its a long code, thus I'm pasting just a part of it... Up we have fetching
Any ideas are very appreciated.
Just before creating img element "createDet" you can create button element for deleting
var closeBtn = document.createElement('button');
closeBtn.innerHTML = "Close image";
showPicture.appendChild(closeBtn);
closeBtn.addEventListener ("click", function() {
var showPicture = document.getElementById("showPictureID");
var imgTag = showPicture.getElementsByTagName('img')[0]; //or use more precise selection for image that must be closed
showPicture.removeChild(imgTag);
var btnTag = showPicture.getElementsByTagName('button')[0]; //remove the close button too
showPicture.removeChild(btnTag);
});
Style the button with css as you wish.
If showPicture contains only the picture, you can just empty it, but you should use only one of event listeners not both.
closeBtn.addEventListener ("click", function() {
var showPicture = document.getElementById("showPictureID");
showPicture.innerHTML = '';
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.