1

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.

Mark
  • 16,906
  • 20
  • 84
  • 117

1 Answers1

1

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/

Community
  • 1
  • 1
Julien Grégoire
  • 16,864
  • 4
  • 32
  • 57
  • It works, however, a lot of time when I drag the text in it will remove a character from the text, have you noticed? (Safari) – Mark Jun 23 '15 at 06:52
  • I didn't look at it on Safari, but yes, now I see it, there's a weird behavior, but it's not only on drag, it seems to do it with your Do something button as well? Seems to be a problem with execCommand insertHTML altogether. Maybe add some steps, like adding a whitespace set the range before that space and then insert. Seems overly complicated, but it really looks like a bug. – Julien Grégoire Jun 23 '15 at 13:11