As the title states, I would like to use my cursor's position as the start point to a range.
Right now have simple sample like this
<html>
.
.
<p>The quick brown fox jumps over the lazy dog</p>
.
.
</html>
On the CS/JS side of things I have event listen set to mouse move that attempts to print out the offset for the cursor position, however I am not using the correct method and end up getting either undefined
or no method error
s.
Again, really simple CS for the time being since I really just wanted to test it out.
$(document).ready ->
$(document).mousemove ->
target = event.target
console.log("#{target.offset()}") // also tried .rangeOffset .offset
Ideally I would like something that I can input into a range.setStart()
function.
For example, if I was to be moused over the f in fox I would want the offset to be return as 16 so that I may then set the start of the range like so range.setStart(target,16)
.
Any help setting me in the right direction would be greatly appreciated.
edit: After typing this up and submitting it I realized how silly it was to expect the element to give me back offset information. I am terribly lost, please guide me.
You should be using pageX or pageY, like thisIf you need to get the position relative to a div for example
Applied to your case, it would give you something like this
And moving your mouse over the paragraph containing your text will give you your mouse position inside the paragraph
see it working here http://jsfiddle.net/zXnk9/
EDIT
If you need to get the index of the character you are hovering you could use a trick like so:
Wrap your text inside a container that is exactly the width of your text
And then make the following calculation
You can check it working here. I've set the event to click so that you can try it precisely on the f of fox, it returns 16. http://jsfiddle.net/zXnk9/1/
EDIT 2: for a reliable way of doing what you are trying to do
When loading the document, put every character inside the container into an html node, like this
Then you can just get the index of the character on which your mouse is positionned with the following
This will work with multi line containers, with paragraphs, etc.
See working example http://jsfiddle.net/2TBFV/
After much googling and many hours of troubleshooting I finally came up with a solution that works for my purposes.
The function
document.caretPositionFromPoint()
or for Webkitdocument.caretRangeFromPoint()
takes X and Y coordinates from an event and returns a caret position that I can then use to create the start point of my range with.