Tuesday, March 15, 2011

In Javascript, can I get the exact coordinates on text cluttered with tags (childNodes everywhere?)

Hi,

See the example below: it shows lines of text in a table (there's a good reason for this, but that's not the issue here).

Basically, all I need is a function that alert()'s me the perfect coordinates of the text selection when I click on the link. By perfect coordinates, I mean: line number of the start of the selection, line number of the end of the selection (those two are trivial-esque, I just use the number in the <td> id, offset of the start of the selection, offset of the end of the selection.

So, if I select

first line and it contains text
This is the second

I get an alert that says:

selection starts at line 1, offset 12
selection ends at line 2, offset 18

It would be really easy with getRange() (I do not need Internet Explorer compatibility so getRange() which work for FireFox, Chrome and Safari is OK) if the text was plain text. The issue here is that <span>, <strong> and <em> tags are everywhere and that each of them is a new childNode. So getRange() doesn't work.

I have not found a way to ignore markup. It seems there's no easy way to do that. But I'm no Javascript expert and maybe that there's a trick to ignore (or to make the function act as if it ignored) the tags in the text.

<a href="javacript: magicCode();">Select some text in the table then click here</a>
<table>
<tr>
<td id="content1">This <span class="one">is the</span> first line <span class="two">and it contains</span> text</td>
</tr>
<tr>
<td id="content2">This is the <span class="three">second line and it contains text</span></td>
</tr>
<tr>
<td id="content3"><span class="four">This is <span class="five">the third</span> line and it</span> contains text</td>
</tr>
<tr>
<td id="content4">This is <strong>the fourth <em>line</em> and it</strong> contains text</td>
</tr>
<tr>
<td id="content5">This is the fifth line and it contains text</td>
</tr>
</table>

Could anyone help my write my magicCode()?

Thanks!

From stackoverflow
  • You can use the .textContent property to get just the text values without the HTML. You could easily make it work in all browsers as well by checking for .innerText and using that if it exists, otherwise use .textContent. innerText works in IE and textContent works in Firefox/Chrome etc.

    Here's a sample of that:

     var content = document.getElementById('content1');
     if(content.innerText){
       alert(content.innerText);
     }else{
       alert(content.textContent);
     }
    
  • You may want to look into using the canvas tag to generate your text; it may be a bit complicated and over-the-top for your project.

    Bespin is a code editor created entirely with the canvas tag. I haven't look at the source so I can't tell you how they manage to render text and mimic text selection.

    https://bespin.mozilla.com/

0 comments:

Post a Comment