1

This is a follow-up to this question about contenteditable and rich text editing. I'm using HTML5 and JavaScript in a recent Firefox (21 beta 7 on Linux).

I want a content-editable <p> paragraph (or perhaps later, <div> block element) in which the user input words are shown in two different ways (probably <span class='name'> and <span class='word'>) depending if they are known or not. So if the user has typed foo john and foo is an unknown word but john is a known name the two words would be rendered differently, and the editable paragraph would contain

<p><span class='word'>foo</span> <span class='name'>john</span></p>

When I am getting a keypress event I know its target element. But how can I know the character offset in that element. In other words, if the element is some text node or span containing jon and if the caret is after jo and before n and if I'm typing the h character how can I get the offset 2?

Of course I have a JavaScript knownname function which returns null if its argument -some string- is not a known name but a plain word, and some true value if it is known.

BTW, I want plain JavaScript. Later, that JavaScript will be generated (and I am beginning to learn how to do that generator).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    Take a look at [selection](https://developer.mozilla.org/en-US/docs/DOM/Selection) and [range](https://developer.mozilla.org/en-US/docs/DOM/range). :) – Dagg Nabbit May 08 '13 at 09:39
  • @DaggNabbit: Thanks! do you have some good tutorial material (preferably website) to advise me to read? – Basile Starynkevitch May 08 '13 at 09:45
  • Is a `contenteditable` paragraph the good approach for simple rich text editor, or should I use `textarea`? Then, how can I change the style or look of individual words inside? – Basile Starynkevitch May 08 '13 at 09:49
  • [Tim Down](http://stackoverflow.com/users/96100/tim-down) is pretty much the authority on this stuff as far as I know, you might want to look at the source of his [rangy](http://code.google.com/p/rangy/) library. `contenteditable` is the way to go, you can't style individual parts of a textarea. – Dagg Nabbit May 08 '13 at 09:51

0 Answers0