Get text offset from click event via Javascript?

So, I searched everything, trying to figure out how to do the following and still not 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 the user clicks on the first “a” in the sentence, the text shift will be 8, since the first “a” is at index 8, if we take the “T” in 'This' as index 0.

I need this information so that I can programmatically create a selection of text based on where the user clicks. At the moment, I can track which HTML elements we click on, and therefore I can create this kind of activity at the level of detail at the HTML level, but I would like to have finer control than that.

Thank!

+5
source share
6 answers

Copied from your comment in another answer:

I'm currently trying to model human behavior through Javascript, which turns out to be a bit more complex than I expected (most probably by design).

What you need is Selenium to automate your web browser: http://seleniumhq.org/

+2
source

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 do not do this for large blocks of text (or, preferably, in general). It creates a DOM node for each character and can slow down the browser ...

+2
source

, -. .

, API , , , .

+1

/.

mouseX offsetY dblclick , , API , , . , .

+1

span onClick, span span . .

+1

Try it window.getSelection()... I'm not sure if it works in all browsers, but at least Chrome seems to create the Selection object with the offset you need.

0
source

All Articles