I’m trying to create an image uploader that can can upload an image and display it in another div. So far I have been able to display the image but let’s say I change my mind and backspace the image(which deletes the image) and then again when i try to upload the second time around(without refreshing the page), the image doesn’t appear at all. I even doubt if the change function runs the second time around(console.log doesn’t fire). Can you tell How I can upload image without refreshing? I have set the multiple ="true"
on input tag as well.
edit: (added snippet on request). As per the mina’s answer, changed my code to input.value = ''
. It was not there in the original posting.
document.querySelector('.imageUploader').addEventListener("click", function(e){ document.querySelector('.imageInput').value= ''; document.querySelector('.imageInput').click(); document.querySelector('.imageInput').addEventListener('change', ev => { let theFile = ev.target.files for (var i = 0; i < theFile.length; i++) { let reader = new FileReader(); reader.readAsDataURL(theFile[i]); reader.onload = function(){ let dataURL = reader.result; let el = document.createElement("img") el.setAttribute('src', dataURL ) let node = document.querySelector('.textDiv') node.appendChild(el); } } }) })
<div class="imageUploader" style="width:50px; height: 50px; background-color: gray"></div> <input type="file" class="imageInput" name="file" style="display:none;" multiple="true"/> <div class="textDiv" contenteditable="true" style = "border: 1px solid black; height: 200px;"> </div>
Advertisement
Answer
It’s all about change
event, it will not re-execute except if you choose another image/file.
So to make it able to choose the same image
again you need to reset the input file
value.
input.value = ''
document.querySelector('.imageInput').addEventListener('change', ev => { let theFile = ev.target.files for (var i = 0; i < theFile.length; i++) { let reader = new FileReader(); reader.readAsDataURL(theFile[i]); reader.onload = function(){ let dataURL = reader.result; let el = document.createElement("img") el.setAttribute('src', dataURL ) let node = document.querySelector('.textDiv') node.appendChild(el); } } }) document.querySelector('.imageUploader').addEventListener("click", function(e){ document.querySelector('.imageInput').value= ''; document.querySelector('.imageInput').click(); })
<div class="imageUploader" style="width:50px; height: 50px; background-color: gray"></div> <input type="file" class="imageInput" name="file" style="display:none;" multiple="true"/> <div class="textDiv" contenteditable="true" style = "border: 1px solid black; height: 200px;"> </div>