Home > front end >  Image Doesn't Appear On Preview If Re-Added After Deletion - JavaScript
Image Doesn't Appear On Preview If Re-Added After Deletion - JavaScript

Time:10-03

I have an image uploader that I'm building that allows the user to remove images/ image previews prior to form submission. I seem to have a come across a side effect that a) I don't know what is causing it, and b) how to fix it.

When an image is deleted from the preview the image is removed via a click event and the remove() method on the image's parent figure element.

If a user then re-selects the same image (that has just been removed) from their computer with the file picker / input the image doesn't show on the preview the second time around? But, even more confusingly, if a completely different image is attached, and then the user tries to re-attach the original image that previously didn't show the second time, that image does then show again (I hope this makes sense).

I have no idea what is going on here?

In the code sandbox if you add an image, delete it from the preview, then re-add you'll see what I mean.

CodePen: https://codepen.io/thechewy/pen/abGGaoZ

let dropZone = document.getElementById("zone"),
  showSelectedImages = document.getElementById("show-selected-images"),
  fileUploader = document.getElementById("upload-files");

dropZone.addEventListener("click", () => {
  // assigns the dropzone to the hidden input element, when you click 'select files' it brings up a file picker window
  fileUploader.click();
});

// Prevent browser default when draging over
dropZone.addEventListener("dragover", (e) => e.preventDefault());

// Prevent browser default when draging over
dropZone.addEventListener("drop", (e) => e.preventDefault());

fileUploader.addEventListener("change", (e) => {
  // this function is further down but declared here and shows a thumbnail of the image
  [...fileUploader.files].forEach(updateThumbnail);

  console.log("fileUploader.files is: ", [...fileUploader.files]);
});

// updateThumbnail function
function updateThumbnail(file) {
  if (file.type.startsWith("image/")) {
    let uploadImageWrapper = document.createElement("figure"),
      thumbnail = new Image(),
      removeImage = `
            <div > Delete </div>
            `;

    // image thumbnail
    thumbnail.classList.add("thumbnail");
    thumbnail.src = URL.createObjectURL(file);

    // appending elements
    showSelectedImages.append(uploadImageWrapper); // <figure> element
    uploadImageWrapper.append(thumbnail); // image thumbnail
    uploadImageWrapper.insertAdjacentHTML("afterbegin", removeImage); // 'x' to remove image

    // get the original width and height values of the thumbnail using the decode() method
    thumbnail
      .decode()
      .then((response) => {
        thumbWidth = thumbnail.naturalWidth;
        thumbHeight = thumbnail.naturalHeight;

        // typical front end image validations
        if (thumbWidth * thumbHeight < 4000000) {
          // output the error message
        }
      })
      .catch((encodingError) => {
        // Do something with the error.
      });

    // Delete images from the preview
    document
      .querySelectorAll("#show-selected-images .remove-image")
      .forEach((i) => {
        i.addEventListener("click", (e) => {
          if (e.target) {
            var deleteFigureEl = e.target.closest("figure");

            // removes the image via removing it's parent element
            deleteFigureEl.remove();
          }
        });
      });
  }
} // end of 'updateThumbnail' function
body {
  margin: 0;
  display: flex;
  justify-content: center;
  font-family: arial;
}

form {
  width: 50%;
  max-width: 600px;
}

.select-files {
  padding: 1rem;
  background: red;
  cursor: pointer;
  color: #fff;
  font-weight: bold;
}

#show-selected-images {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-top: 2rem;
}
figure {
  width: 100%;
  margin: 0;
}
img {
  display: block;
  width: 100%;
  height: auto;
}

.remove-image {
  cursor: pointer;
  padding: 1rem;
  background: lightgrey;
}
<form id="upload-images-form" enctype="multipart/form-data" method="post">
  <h1>Upload Your Images</h1>
  <div id="zone">
    <p >SELECT FILES</p>
  </div>
  <div >
    <div >
      <input id="upload-files" style="display:none;" type="file" name="upload-files[]" multiple>
    </div>
    <button id="submit-images" oninput="updateThumbnail(this.files)">SUBMIT</button>
  </div>
  <div id="show-selected-images"></div>
</form>

CodePudding user response:

just add

fileUploader.value = "";

/

document
        .querySelectorAll("#show-selected-images .remove-image")
        .forEach((i) => {
            i.addEventListener("click", (e) => {
                if (e.target) {
                    var deleteFigureEl = e.target.closest("figure");

                    fileUploader.value = "";
                    // removes the image via removing it's parent element
                    deleteFigureEl.remove();
                }
            });
        });
  • Related