I have an image previewer that uses the JavaScript Image() object to preview images prior to them being processed with PHP. I have a div that contains an 'x' SVG graphic that is targeted with a click event to delete the image.
In the code below at the bottom of the function it uses evt.target and essentially removes the parent element that each image is inside to delete the image if the user wishes to do so.
This all works OK on a visual level, but even if the images are deleted (and they are removed from the HTML), when the 'submit' element on the form is clicked to upload the images, any deleted images are still processed. From what I can gather the images are stored in memory and are processed from there.
I've tried setting the image itself (the thumbnailElement in the JavaScript) to null and setting its src attribute to an empty string but this isn't working.
What is the best way to prevent these deleted image previews from being processed?
In the code below I've swapped out the SVG graphic for the 'x' to the letter 'x' to make it easier to read.
Note: It's probably better to view it in the context of the full image uploader here if the Javascript below isn't sufficient, to ensure any code doesn't cause side effects: https://codepen.io/emilychews/pen/WNjZVGZ
function updateThumbnail(file) {
if (file.type.startsWith("image/")) {
// image and 'x' to delete wrapper
const uploadImageWrapper = document.createElement('article')
// div that holds the 'x' to delete
const removeImage = document.createElement('div')
// image preview element
thumbnailElement = new Image()
// 'x' that deletes the image
removeImage.classList.add("remove-image")
removeImage.innerHTML = 'x'
// image thumbnail
thumbnailElement.classList.add("drop-zone__thumb")
thumbnailElement.src = URL.createObjectURL(file)
// appending elements
showSelectedImages.append(uploadImageWrapper) // <article> element
uploadImageWrapper.append(removeImage) // 'x' to delete
uploadImageWrapper.append(thumbnailElement) // image thumbnail
// Delete Images when the 'x' div is clicked
removeImage.addEventListener('click', (evt) => {
if(evt.target) {
var deleteImage = removeImage.parentElement
deleteImage.remove()
thumbnailElement = null
thumbnailElement.src = ''
}
})
}
} // end of 'updateThumbnail' function
from Delete An Image() Object From Memory On Click Event Of Sibling Element — JavaScript
No comments:
Post a Comment