How can you drop an image from your desktop into an editor and move it around?

158 Views Asked by At

The default behavior when you drop something from your desktop to a textarea is that you will see the path to the image at the position where you dropped it. My end goal is to convert the local image as base64 and insert it at the drop position within the text. To accomplish this I like to start to insert text at the drop position.

But when I use document.execCommand('insertHTML',null','<b>Some Text</b>'); it will not insert it at the position where my cursor was when I dragged the image in there, but it will insert it at the position my cursor was before I began dragging. Does anyone know how to insert the text at the drop position?

I created a fiddler at: http://jsfiddle.net/cqjhm9c5/ Try and drag a local image file from your desktop into the text.

enter image description here

UPDATE + ANSWER

Thanks to Julien helping me in the right direction, I created the following snippet: http://jsfiddle.net/8kodh94k/7/

This will allow you to drop an image from your desktop into the text and move it around.

1

There are 1 best solutions below

2
On BEST ANSWER

You can set the caret from your mouse position.

See Text selection in div(contenteditable) when double click

Didn't try it on IE, but this seems to work on Chrome/Firefox:

function userDidDrop(event) {
    event.preventDefault();
    if (document.caretRangeFromPoint) { //Chrome
        range = document.caretRangeFromPoint(event.clientX, event.clientY);
    } else if (document.caretPositionFromPoint) {//Firefox
        rangePos = document.caretPositionFromPoint(event.clientX, event.clientY);
        range = document.createRange();
        range.setStart(rangePos.offsetNode, rangePos.offset);
        range.collapse(true);
    } else if (document.body.createTextRange) {//IE
        var range = document.body.createTextRange();
        range.moveToPoint(event.clientX, event.clientY);
        range.select();
    }
    window.getSelection().removeAllRanges()
    window.getSelection().addRange(range)

    document.execCommand('insertHTML', null, '<b>Drop</b>');
}

http://jsfiddle.net/ozw6fLv5/1/