I'm trying to allow a user to click a file upload button, select a file, and have that file immediately display wherever they are typing in a contenteditable div. I have a solution that works inconsistently, and seems to depend on which element is focused before the file upload is clicked.
This is similar to this question, except that I cannot get the proposed solution to work reliably:
insert image inside a contenteditable div
Here is an example that works sometimes, but every time I run it it is hard to predict whether or not the image will show. I'm trying to make this work reliably.
https://jsfiddle.net/0tdgc49k/1/
Note that I am clicking on the label, not the input element, which should trigger the same event. Uploads using the input element seem more reliable, although I would ideally like to get the label element working because it is easier to style.
function pasteImage() {
document.getElementById("output").focus();
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById("output").focus();
document.execCommand('insertImage', false, e.target.result);
}
reader.readAsDataURL(document.getElementById("input").files[0]);
}
document.getElementById("input").addEventListener('input', pasteImage);
document.getElementById("output").focus();
input {
opacity: 0;
}
<label for="input">Upload Photo</label>
<input id="input" type="file" accept="image/*">
<div id="output" tabindex="0" contenteditable="true">Editable Content</div>
I expect that every time I click "Upload Image" and select an image from my harddrive, it will become visible in the contenteditable div. Sometimes it does, but if I repeatedly run the fiddle and attempt the upload again, it fails about half the time. This result is consistent across both the fiddle and the local html page on which I developed it, so it is not just an artifact of the fiddle.