Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using a drag & drop, pulling labels of text over to a textbox on a webpage. On drop I would like to have it insert the text of the label where the mouse is using jquery.

Unfortunately I can't see a way to determine where the caret would be based on the current mouse position other than getting the relative position of the mouse to the textbox element and working out all of the text font/size/kerning/line-height/newlines/etc.

The browser itself can easily work this out (click the textbox, there's the caret in the right position), but I can't see how to do this in code.

Any help on would be appreciated.

Again, my goal is to drag a label to a textbox and have it drop into the current text based on the position of the mouse using jquery. Although if it gets the job done, I'd use whatever is available. Everything is already done apart from determining the position in the text where the label is dropped.

Cheers!

What I have tried:

So far I've tried using what in-built methods and properties I can find in asp.net and have started on trying to determine the correct position of the caret based on mouse position and the textbox's text. This however, seems like a big workaround for something usually achieved by just clicking the textbox text, so I'm hoping I'm missing something obvious before I continue on this path.
Posted
Updated 12-Jul-19 5:03am
v4

1 solution

You will most likely have to do this via JavaScript since you are working with an HTML element of
HTML
<input type="text">

Fortunately, there is a well-accepted solution to this at:
javascript - Need cursor at beginning of text in textarea - Stack Overflow[^]

I've altered it a bit and created a plunker so you can try it out:
Plunker - Set Caret Position[^]

Here's a quick snapshot:
https://i.stack.imgur.com/O17ns.png[^]

You can
1. set the value where you want to see the caret be located at (first input - number)
2. click the button
3. see the caret be set in the (second input -- text)
 
Share this answer
 
Comments
Member 14528514 22-Aug-19 5:01am    
Unfortunately the main issue is working out the index based on the position of the mouse over the textbox. Imagine moving your mouse over the textbox and seeing a label with a changing index that matches your mouse position's index.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900