I am working on creating an image upload function using JavaScript, but encountering an issue. When I delete the first image (by clicking the 'X') and try to re-upload another image, both images appear instead of just one. I need to resolve this using only JavaScript without any external libraries. Below is the code snippet:
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>