views:

36

answers:

2

Hello all, If I have a string in a div

<div id="article">
 lots of text goes here
<strong> it's really interesting</strong>
and it's free to read
</div>

if a user double click or single click on a particular word, is there a way to determine the position/index of the character clicked?

If that cannot be done, how about determining how many space character there are before the clicked position. So if I click on the word 'goes' in the above example, it returns 3 because there are three spaces before the word goes which is clicked.

Thank You very much for your time.

A: 

The ugly hack solution to such a problem involves programming converting the characters into event capturing objects.

For instance

<div id="article">
<span>lots </span><span>of </span><span>text</span>...
</div>

Now this can be done programmatically. You can grab whatever the current content of a div and convert it to something like the formatting above. Then attach event handlers to the contained spans which count the number of spans preceding it in the same container.

Jamie Wong
I see. So I will be doing a replace(/(\b\w*\b)/, '<span>$1</span>'), is this right?
Nik
I'd also include the trailing spaces (so you capture the event even if the user clicked on a space between words). To attach the events, try using document.getElementById('article').getElementsByTagName('span') and loop through them attaching the same onclick event handler.
Andrew
@Andrew That's a good point. Not capturing the clicks on spaces would be annoying. Edited to reflect
Jamie Wong
A: 

a way to determine the position/index of the character clicked

Well, first I need to use a fixed width size font like Courier. Then, I'd create two span with only a char each. With those two, I should be able to know the width of a char (beware padding and margin) and its height. Then, you need to know your upper left coordinates for your div whose id is 'article' and capture click event with event.x and event.y.

After that,

var line = (event.x - divLeft) / charHeight; 
var column = (event.y - divTop) / charWidth;
That's a cool solution. I think the line breaks would be problematic unless they were manually inserted. You'd also need to derive your `charHeight` and `charWidth` because you can't count on the same values across platforms. This wouldn't work if you had scroll bars showing up for longer text, but you could also build (or rebuild) the string character-by-character to see where the line breaks were. You could also use this technique to map out the x/y coordinate of each letter -- but that's massive overkill.
Andrew
I was gonna say that! I will experiement with both and come back to see which offers what advantage that's to my project only, of course. but both solutions make sense
Nik
Scrolls, good catch...