javascripthtmlcreateobject

insert image in a iframe at caret location


For a rich text box. I want to insert a picture, selected by the user, at the caret's position.

First I tried that:

var loadImage = function(event) {
    var editor = editFrame.document;
    editor.execCommand("insertImage", false, event.target.files[0] );
};

I get only a broken link icon but at the current position in my iframe. No image. Then I've been told to try that:

var loadImage = function(event) {
    var editor  =  document.getElementById('editFrame');
    editor.src = URL.createObjectURL(event.target.files[0]);
};

Which is not what I want to do but in this case I don't have broken link problem and the image loads normally.

How can I get the best of the 2 worlds? :)

Can somebody explain me how to load an image where expected; at the caret position? I read some stuff but being a beginner it's all very confuse in my mind.

Using only javascript, please? I mean the solution offered by @David Bray works fine. But it uses JQuery and I have no clue what it's doing whatsoever... Or could someone translate me the JQuery into Javascript?


Solution

  • take 10 and using How to get the image element after insert using execCommand?

    <html>
        <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        </head>
        <body>
            <form id="form1" runat="server">
                <input type='file' id="imgInp" />
    
            </form>
    
            <div contenteditable id="doc">type here .. put you cursor here [.] and put an inmage in the queue</div>
    
            <script>
            function readURL(input) {
    
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
    
                    reader.onload = function(e) {
                        $('#doc').focus();
                        document.execCommand("insertHTML", false, "<img src='" + e.target.result + "' />");
                        console.log( 'done');
    
                    }
    
                    reader.readAsDataURL( input.files[0]);
                }
            }
    
            $("#imgInp").change(function() {
                readURL(this);
    
            });
    
            </script>
    
        </body>
    
    </html>