2

I am writing code in GWT (Google Web Toolkit) with some embedded JavaScript.

I have a RichTextArea, and I need to find out the absolute character position within that RichTextArea (which is a Document living in an iframe) when I've been supplied with a Selection object (from which I can get Range objects).

The problem is, the Selection/Range api is very relativistically designed - it can tell you what text node you're in, what the parent Element is, etc. but doesn't seem to easily be able to provide the absolute character position within the Document itself.

I've found related questions and issues discussed here, but this one in particular is something I haven't found.

I suppose I could get the text node that the Selection starts in, and search/traverse the Document looking for it and adding character offsets as I go; that seems rather brute-force. Does anyone know if there is a way to get the character offset into the Document of a given Selection/Range more directly? You would think this kind of information would be easily supplied by the browser, but I haven't found a solution to this one.

Ean V
  • 5,091
  • 5
  • 31
  • 39
tbessie
  • 21
  • 4

1 Answers1

3

There's nothing easy built in. You can ease the pain slightly by using another range spanning the portion of the DOM between the start of the contenteditable element and the start of the selection and calling toString() on it, as in the saveSelection() function in this example:

https://stackoverflow.com/a/13950376/96100

A similar example for just the caret is here, together with notes about shortcomings of this approach (line breaks implied by <br> elements and block elements not contributing to the character count, for example):

https://stackoverflow.com/a/4812022/96100

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Yes, I saw those; it didn't seem like they're be 100% correct in all cases (eg. you mention embedded CSS and JavaScript). I had hoped that the JavaScript engine of any given browser had an internally consistent String representation of any given DOM, so that doing what I want could be done dependably. I'm still amazed that simple things like this need to be done with tricks and jumping through hoops, given how much HTML/CSS/JavaScript is being forced to do these days. I examined how Yahoo Mail and Google Docs work, and they seem to leave text components behind and do everything by hand. – tbessie Feb 05 '14 at 01:36
  • @tbessie: There is no standard for "the text the user sees" and it's a tricky thing to define precisely. I've had a go at making something like that here: http://rangy.googlecode.com/svn/trunk/demos/textrange.html. If you just want to limit yourself to ignoring the contents of ` – Tim Down Feb 05 '14 at 10:14