When you drag a file from your OS filesystem over a textarea or text input, a cursor appears near the mouse pointer (this is different from positionStart
), showing the user where the dragged content would be inserted.
UPDATE: here is an image, I'm dragging a file (test.sh) over the text input. You can see the drop cursor if the middle of the "text" word. The selection cursor is at the end of the string (not visible on this picture).
(Chrome's default behavior is to open the dropped file, but I'm overriding this behavior in the drop
event. I want to insert the name of the file in the textarea.)
I'm trying to get this position (in terms of index in the textarea value string) when drop
occurs. Any idea?
Phew, what you want to do isn't easy, since there is no way to reference this specific caret!
Off the top of my head, you could only implement this through heavy workarounds: What you can obtain upon drop
occuring is the mouse cursor position.
You would have to make an invisible div-clone identical to the textarea in shape, text-size, margins, etc that automatically gets filled with the text from your textarea.
Next you'd have to create a span for each possible caret position (i.e. 1 span for every character of text) inside this div and get each span's x and y coordinates and save them into an array.
.txtarea {
width: 300px;
height: 150px;
font-size: 12px;
font-family: Arial;
padding: 5px;
text-align: left;
border: 1px solid red;
}
<textarea class="txtarea">Mytext</textarea>
<!--just an example, auto-fill this content through a JS oninput event -->
<div class="txtarea"><span>M</span><span>y</span><span>t</span><span>e</span><span>x</span><span>t</span></div>
Then, upon drop
occuring, get the mouse coordinates of the event, compare them to the array of coordinates, approximate the closest x/y position and set a new selectionStart
index in your textarea based on that, insert the file name, and then restore the previous selectionStart.