Click here to Skip to main content
14,239,876 members
Rate this:
Please Sign up or sign in to vote.
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

You will most likely have to do this via JavaScript since you are working with an HTML element of
<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)
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100