1

I'm working on a way to create annotations in HTML text using JavaScript. The way it works, the user clicks on a contenteditable <div> and I get the position of the cursor based on where they click. Then, when I'm placing the annotation in the text, I go to that character position to insert a footnote indicator. The problem is that the position of the cursor in the contenteditable <div> doesn't take HTML tags into account. So for example, if the <div> contained the following:

AB<b>CD</b>EF

And I placed the cursor between "C" and "D", the position is 3 because it ignores the <b>. Is there a way to get the cursor position including HTML tags so that it is consistent when I go back and place my markers? The <div> doesn't necessarily need to be contenteditable if that opens up other solutions.

(I'm currently using this solution to get the position: Get a range's start and end offset's relative to its parent container)

Zak
  • 2,688
  • 4
  • 29
  • 45
  • You don't need value you described to insert a HTML node at cursor location. `window.getSelection().getRangeAt(0).insertNode()` will do the trick. – weaknespase Mar 30 '16 at 15:55
  • The problem is I'm not inserting it directly into the node. I need to store the location and insert it at a later time – Zak Mar 30 '16 at 19:35

1 Answers1

0

I think it's because <b> is no container and <div> is a container. I didn't try the code but try to assign "display: inline-block" to <b> so it gets recognised as a container. Maybe it works.

Jaycaponex
  • 65
  • 7
  • The problem here is that the selection ignores the HTML markup that isn't displayed in the browser all together. It's starting from the correct container, it just jumps over the html tags themselves when counting the position. – Zak Mar 30 '16 at 20:57