SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : WYSIWYG HTML Editor : Add Formatting Commands

By adding script you can turn the plain text editor into a full-blown rich HTML edit control. The easiest way to script the editor is to use the document selection object. From the selection object you can access the createRange() method that returns a text range representing the current selection. The text range provides an object model over the content of the HTML document compared to the structural view provided by the all collection. For example, the all collection gives you access to the HTML elements that make up the document. From these elements you can access the text within them. The text range object, on the otherhand, provides access to any text in the document, regardless of the elements they are contained within. Through the text range object, you can determine what elements are influencing the text.

To add the correct HTML formatting to the document, you can take advantage of functionality built into the text range object. The text range object exposes a method, execCommand() that executes different formatting commands against the editor. For example, to make text bold, you call execCommand("bold") and Internet Explorer automatically inserts the appropriate <B> tags. Using the execCommand methods, you can quickly create an editor:

<IFRAME WIDTH=200 HEIGHT=200 ID=myEditor></IFRAME>
<SCRIPT>
  function makeBold() {
    // Get a text range for the selection
    var tr = frames.myEditor.document.selection.createRange()
    // Execute the bold command
    tr.execCommand("Bold")
    // Reselect and give the focus back to the editor
    tr.select()
    frames.myEditor.focus()
  }

  frames.myEditor.document.designMode = "On"
</SCRIPT>
<INPUT TYPE="button" ONCLICK="makeBold()" VALUE="Bold">

The execCommand method supports different types of commands for creating headers, paragraphs, lists, bold and italicized text, setting colors, adding undo and redo buttons, and much more. In addition, there are methods for querying the document to determine the current formatting. For a complete list of commands, see the Command Identifier page in the Microsoft SDK. You can also find more information on the TextRange object in the Microsoft SDK and in Chapter 14 of the book Inside Dynamic HTML.

The next step is to enable submitting the contents of the HTML editor with a form.