I'm trying to make a file preview and I had an issue while creating a function to remove the image uploaded. I need to create a function that removes the image uploaded and shows the default picture that I have. Let's suppose that I have an account with a picture and then I want to change it, but when I uploaded a file I didn't like it and want to click in a button that will remove this new picture and get back to the first one (let's say that I didn't save it). So, in all cases I need to store the first src in a variable and then use it later if it's necessary. I'll reproduce here the code that I created to preview the file (it's working good). Now I need help to create the remove function following the requirements I said before. If it's possible, without jquery.
const inpFile = document.getElementById("inpFile");
const previewContent = document.getElementById("imagePreview");
const previewDefaultText = previewContainer.querySelector(".previewText");
const previewImage = previewContent.querySelector(".previewImage");
inpFile.addEventListener("change", function(){
const file = this.files[0];
if(file){
const reader = new FileReader();
previewDefaultText.style.display = "none";
previewImage.style.display = "block";
reader.addEventListener("load", function() {
previewImage.setAttribute("src", this.result);
});
reader.readAsDataURL(file);
}
})
Save the original source in a dataset property.
inpFile.addEventListener("change", function() {
const file = this.files[0];
if (!previewImage.dataset.origSrc) {
previewImage.dataset.origSrc = previewImage.src;
}
if (file) {
const reader = new FileReader();
previewDefaultText.style.display = "none";
previewImage.style.display = "block";
reader.addEventListener("load", function() {
previewImage.setAttribute("src", this.result);
});
reader.readAsDataURL(file);
}
})
removeButton.addEventListener("click", function() {
if (previewImage.dataset.origSrc) {
previewImage.src = previewImage.dataset.origSrc;
previewImage.dataset.origSrc = '';
}
});