A live, echoed preview is relatively simple to set up. You begin by capturing the keyup event in either a form textarea or input element, and take all of the text and reflect it in an associated div element through the innerHTML property.
In the code, you do need to adjust the text, replacing the hard carriage returns with a break element, br. This keeps the text more or less in sync with the input.
Example 4-9 includes a complete application that uses live preview. Since the example is so small, the stylesheet and script are both included within the web page. The previewed text isn't modified other than transforming the carriage break into a br. If you want to modify the text preview in other ways, such as stripping HTML tags to reflect what the comment will look like published, you'll need to adjust the script accordingly. Remember, though, to keep the preview simple--the function to live preview the input is called whenever a keyup event happens in the form element.
Whatever is typed into the textarea is reflected in the preview element.
The form also has Preview and Save buttons, both of which go to the preview.php page. From there, a user can save the comment or click the Back button to return to the form and continue editing. Neither requires script. Later on in this chapter, we'll see how we can submit the form and display the new comment, all without leaving the page.
There's one major problem with live preview, and that's what happens when the page is served with an XHTML MIME type. The way that browsers implement innerHTML differs among applications, though most do support some version of innerHTML. However, what happens during live preview if you begin to add an XHTML tag differs dramatically between browsers. In Firefox 2.x and up, the incomplete tag throws dozens of errors until it's completed, all of them saying the text is not well-formed XML. In Opera, however, the browser treats the incomplete tag as escaped content until the tag is closed, in which case, it then treats it as XHTML.
A workaround is to escape HTML characters, <, >, and &, replacing the modText generation with the following:
This disables the links and other HTML. In nontrusted situations, you may want to consider completely stripping out all HTML.
The differences in behavior between browsers is significant enough that you'll probably want to use live preview only with pages served as HTML, at least until the new HTML 5.0 standard comes out, which should clarify how a document fragment is managed. In the meantime, if you want XHTML and an in-page preview, I'd suggest you use the "Ajax" version of comment preview.
There are many implementations of live preview online, but I first saw it via a Wordpress plug-in created by Chris Davis at http://www. chrisjdavis.org.
Please check back next week for the conclusion to this article.