apply style to range of text with javascript in uiwebview

Posted by drawnonward on Stack Overflow See other posts from Stack Overflow or by drawnonward
Published on 2010-05-22T05:45:45Z Indexed on 2010/05/22 5:50 UTC
Read the original article Hit count: 232

Filed under:
|
|
|
|

I am displaying some simple styled text as html in a UIWebView on iPhone. It is basically a series of paragraphs with the occasional strong or emphasized phrase. At runtime I need to apply styles to ranges of text.

There are a few similar scenarios, one of which is highlighting search results. If the user has searched for "something" I would like to change the background color behind occurrences of the word, then later restore the original background.

Is it possible to apply styles to ranges of text using javascript? A key part of this is also being able to unset the styles.

There seem to be two likely paths to follow. One would be modifying some html in Objective-C and passing it through javascript as the new innerHTML of some container. The other would be to use javascript to directly manipulate DOM nodes.

I could manipulate html, but that sounds tedious in Objective-C so I would rather manipulate the DOM if that is a reasonable approach. I am not that familiar with javascript and DOM so I do not know if it is a reasonable approach.

I wrote some routines to translate between text ranges and node ranges with offsets. So if I start with text range 100-200 and that starts in one paragraph and ends in a third, I can get the text nodes and the offsets within the nodes that represent the given text range. I just need a way to split a text node at an offset in the text. Currently I just apply styles to the paragraphs containing the text range.

A few notes:

  • straight javascript please, no external frameworks like jquery.
  • the changes never need to be written to disk.
  • the changes should be undoable or at least removable.
  • the styles to apply already exist in a css file.
  • it needs to work in iPhone 3.0 and forward.
  • all the source files are shipped with the app.
  • please be verbose.

Thanks for any suggestions.

© Stack Overflow or respective owner

Related posts about html

Related posts about css