I have successfully created a script that shows the preview of an uploaded image on the client-side along with the option to remove it.
However, I am facing an issue with the UI design as the position of the close icon is not aligned to the top-right corner.
Below you can find the code snippet and a JSfiddle link for testing purposes. To test it on JSfiddle, simply add an image using the browse button.
jQuery(function($) {
$('div').on('click', '.closeDiv', function() {
$(this).prev().remove();
$(this).remove();
$('#upload-file').val("");
});
var fileInput = document.getElementById("upload-file");
fileInput.addEventListener("change", function(e) {
var filesVAR = this.files;
showThumbnail(filesVAR);
}, false);
function showThumbnail(files) {
var file = files[0]
var $thumbnail = $('#thumbnail').get(0);
var $image = $("<img>", {
class: "imgThumbnail"
});
var $pDiv = $("<div>", {
class: "divThumbnail",
style: "float: left"
});
var $div = $("<div>", {
class: "closeDiv",
style: "float: right"
}).html('X');
$pDiv.append($image, $div).appendTo($thumbnail);
var reader = new FileReader()
reader.onload = function(e) {
$image[0].src = e.target.result;
}
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
$image.on('load', function() {
ctx.drawImage($image[0], 100, 100);
})
}
});
img {
width: 30%;
float: left;
height: 100px;
width: 100px;
}
.closeDiv {
width: 20px;
height: 21px;
background-color: rgb(35, 179, 119);
float: left;
cursor: pointer;
color: white;
box-shadow: 2px 2px 7px rgb(74, 72, 72);
text-align: center;
margin: 5px;
}
.pDiv {
float: left;
width: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="thumbnail"></div>
<input type="file" id="upload-file" accept="image/*" />