I try to make an upload image file function with javascript, but i have some issue, when i delete (click the 'X') the first image and try reupload with another image it will come with the two same image, which is it should appears only one,i need to make it done with javascript only, without any library, here is my code below.
var container = document.querySelector('.image_container');
function upload(id,imageBox, deleteBtn){
var inputTarget = document.getElementById(id);
var imageBox = document.getElementById(imageBox);
var deleteBtn = document.getElementById(deleteBtn);
var imagePrev = document.createElement('img');
inputTarget.addEventListener('change', function({target}){
var file = target.files[0];
var reader = new FileReader();
reader.onload = function(e){
deleteBtn.style.display = 'block';
imageBox.style.display = 'none';
imagePrev.src = e.target.result;
imagePrev.className = id;
container.appendChild(imagePrev);
};
reader.readAsDataURL(file);
});
}
function deleteImg(id,imageBox,btnId){
var targetInput = document.getElementById(id);
var imageBox = document.getElementById(imageBox);
var imagePrev = document.querySelector('.'+id);
var deleteBtn = document.querySelector('#'+btnId);
imageBox.style.display = 'block';
targetInput.value = "";
deleteBtn.style.display = 'none';
container.removeChild(imagePrev);
}
.image_container input[type="file"] {
display: none;
}
.image_container #image_area1 {
width: 100px;
height: 100px;
cursor: pointer;
text-align: center;
display: inline-block;
line-height: 90px;
background: rgb(211, 211, 211);
border-radius: 3px;
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
.image_container {
display: inline-block;
}
button {
display: block;
margin: 20px 0;
}
#close_button {
background: white;
border-radius: 50px;
width: 21px;
height: 21px;
text-align: center;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div class="image_container">
<label>
<input
type="file"
class="upload_button-first"
id="target1"
onclick="upload('target1','image_area1', 'close_button')">
<span id="image_area1">upload image</span>
</label>
<div id="close_button" onclick="deleteImg('target1','image_area1','close_button')">x</div>
</div>
</body>
</html>