Drop image into contenteditable in Chrome to the cursor Drop image into contenteditable in Chrome to the cursor google-chrome google-chrome

Drop image into contenteditable in Chrome to the cursor


If you can get the co-ordinates of the drop location (which I assume must be possible), you can do it as follows (untested). I'm assuming you've got the co-ordinates of the drop location relative to the viewport as variables x and y and the dropped image as the variable img:

Demo: http://jsfiddle.net/KZqNj/

Code:

var range;// Try the standards-based way firstif (document.caretPositionFromPoint) {    var pos = document.caretPositionFromPoint(x, y);    range = document.createRange();    range.setStart(pos.offsetNode, pos.offset);    range.collapse();    range.insertNode(img);}// Next, the WebKit wayelse if (document.caretRangeFromPoint) {    range = document.caretRangeFromPoint(x, y);    range.insertNode(img);}// Finally, the IE wayelse if (document.body.createTextRange) {    range = document.body.createTextRange();    range.moveToPoint(x, y);    var spanId = "temp_" + ("" + Math.random()).slice(2);    range.pasteHTML('<span id="' + spanId + '"> </span>');    var span = document.getElementById(spanId);    span.parentNode.replaceChild(img, span);}

This will work in recent-ish WebKit, Opera and Mozilla browsers, although only Firefox has an implementation of document.caretPositionFromPoint().

References: