0

I am attempting to use coffeescript/javascript to create a range that returns a few sentences of text when the user rolls over certain texts. I have the offset move 40 places back, however this sometimes means going into a previous node. How do I make this happen properly?

What I have(works as long as I don't leave the node):

//expanding a previously defined range
new_start = range.startOffset- 40
startNode = range.startContainer
range.setStart(startNode, new_start)

try
  new_end = range.startOffset + 60
  range.setEnd(startNode, new_end)
catch e
  range.setEndAfter(startNode) 

As you can see my code isn't very good and makes a lot of assumptions so I someone could lead me in the right direction when it comes to transversing these nodes I would be stupidly happy.

Sample of the markup (which is terrible):

<div id="content"><p>
    <strong>Title Stuffs<br>
     Yep, a random break<br>
     yes, another!</strong>
</p>
<p>
    <a href="http://internet.co">http://itnernet.co</a>
</p>
<br>
<table>
<tbody>
<tr>
    <td>
        <img src="someimage">
    </td>
</tr>
</tbody>
</table>
<p>
    <br>
     Blah blah blah<br>
     <br>
     more words, going to stop here. you get the idea.
</p></div>

This question is a follow up from one of my previous questions.

Community
  • 1
  • 1
SlowBucket
  • 167
  • 1
  • 1
  • 10

1 Answers1

1

After this line:

new_start = range.startOffset- 40

check that the new_start is not negative and set it to zero if it is. Here is the code:

new_start = range.startOffset - 40;
if(new_start < 0)
    new_start = 0;

That is it for your current problem. You do have another problem though. Your end may also overflow the current text. So, you should check if the endOffset < selection.extentNode.length.

Chandranshu
  • 3,669
  • 3
  • 20
  • 37