qadenza
qadenza

Reputation: 9293

insert image inside a contenteditable div

Trying to insert an image inside a div, between lorem and ipsum:

$('#inpfile').on('change', function(){
	var img = $(this).prop('files')[0];
	document.execCommand('insertImage', img);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='file' id='inpfile' accept="image/jpeg, image/png, image/gif">
<br><br>
<div contenteditable>
lorem ipsum
</div>

Nothing happens. Any help?

Upvotes: 2

Views: 6703

Answers (2)

The KNVB
The KNVB

Reputation: 3844

I think my solution should have better readability:

<input type='file' id='inpfile' accept="image/jpeg, image/png, image/gif">
<br><br>
<div id="target">
    lorem ipsum
</div>
<script>
   $( document ).ready(function(){
      $('#inpfile').on('change', function(){
         var targetDiv=document.getElementById("target");
         var file = $(this).prop('files')[0];
         var img=document.createElement("img");
         var reader  = new FileReader();
         targetDiv.append(img);
         reader.addEventListener("load", function () {
            img.src=reader.result;
         }); 
         if (file)
            reader.readAsDataURL(file);
        });
   })
</script>

Upvotes: 0

insertImage requires an image URL and you are passing a file object. Your code actually inserts an <img> tag but without src attribute, which is why you don't see it.

You can retrieve image URL with a FileReader. Here is a working code for what you want to achieve:

$('#inpfile').on('change', function(){
    var file = $(this).prop('files')[0];
    var reader  = new FileReader();

    reader.addEventListener("load", function () {
        document.execCommand('insertImage', false, reader.result);
    }, false);

    if (file)
        reader.readAsDataURL(file);
});

Upvotes: 2

Related Questions