How to add a close button to base64 image preview?

Viewed 444

In a form I'd like to let users to upload multiple images, one by one, and also let them to remove each image by clicking on a x button:

Here is my javascript/jQuery which adds the Base64 image previews to the DOM:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      let image = new Image();
      image.src = `${e.target.result}`;
      image.className = "img-thumbnail add-image-thumb";          
      let closeBtn = `<button type="button" class="close" aria-label="Close">
        <span aria-hidden="true">&times;</span> </button>`;
      $('#images-to-upload').append(image);
      $('#images-to-upload').append(closeBtn);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#imgInp").change(function () {
  readURL(this);
});

And the html part:

 <div id="images-to-upload" class="mb-3"> </div>
 <div class="input-group mb-3">          
    <div class="custom-file">
      <input type="file" class="custom-file-input" id="imgInp" >
      <label class="custom-file-label" for="image-input"></label>
    </div>
    
  </div>
  <small class="form-text text-muted">Upload one or more images</small>

<br>

CSS:

.add-image-thumb{
  max-height: 64px;
  margin: 10px;
  padding: 5px;
}

This works fine for one image, but for multiple images, all x go to the right side of the page.

The problem is how can I put the x button at the top left corner of each image. I could not construct a div out of Base64 images, otherwise I could mangage to acheive that through CSS.

1 Answers

I could not construct a div out of Base64 images, otherwise I could mangage to acheive that through CSS.

Wrap a div around the image

  let wrapper = $('<div class="image-wrapper" />');
  $('#images-to-upload').append(wrapper) 
  $(wrapper).append(image);
  $(wrapper).append(closeBtn);

Use the below CSS

.image-wrapper {
   display: inline-block;
   position: relative;
}
.image-wrapper button {
   position: absolute;
   top: 0;
   right: 0;
 }
Related