Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text offset from click event via Javascript?

So I have searched all over trying to figure out how to do the following and have yet to find a solution:

I need to get the text offset for a given HTML element from a click event. This means that if I have the following HTML

<p>This is a really cool paragraph</p>

and a user clicks on the first 'a' in the sentence, the text offset would be 8 seeing as the first 'a' is at index 8 if we take the 'T' in 'This' as index 0.

I need this information so that I may programmatically create a text selection based on where a user clicks. As of right now I can track which HTML elements are clicked on and thus I can create this sort of activity at a HTML-element level granularity, but I'd like to have finer control than that.

Thank you!

like image 370
MoarCodePlz Avatar asked Dec 05 '11 20:12

MoarCodePlz


3 Answers

Using Prototype:

<p id='mytext'>This is a really cool paragraph</p>
<script type='text/javascript'>
   var characters = $('mytext').textContent;
   var newchars = '';
   for(I = 0;I < chars.length;I++) {
      newchars += '<span id="char_' + I + '">' + chars[I] + '</span>';
   }
   $('mytext').textContent = newchars;
   Event.observe($('mytext'), 'click', function(e) {
      var spanID = (e.findElement('span')).getAttribute('id')
      var index = spanID.split('_')[1]; // Ta-daaa!
   });
</script>

Please don't do this for large blocks of text (or, preferably, at all). It creates a DOM node for every character, and can slow the browser down...

like image 134
Izkata Avatar answered Nov 17 '22 03:11

Izkata


I don't think there's anything built in for that. Any solution will be a hack and unreliable.

What you can do is use the selection API to get a user selection on a page, which sounds like you can do.

like image 1
Alex Turpin Avatar answered Nov 17 '22 02:11

Alex Turpin


Just throwing this out there as a possible hack/solution.

You could try using the mouse offsetX and offsetY when a click occurs and simulate a double click dblclick in that location, effectively selecting the text and then using the selection API to get the word they clicked. Wouldn't work to the letter, but might work to the word.

like image 1
idrumgood Avatar answered Nov 17 '22 02:11

idrumgood