JS: WYSISYG Rich Text Box
Many sites are starting to add rich text boxes, which are text fields that let you create text and alter formatting in a WYSIWYG environment: “What You See Is What You Get”. This basically means a text box that is like a word processor; if you select text and click on the “Bold” button (such as a bold letter B), the text will actually show up in bold.
If such a concept has eluded you, look no further for a detailed tutorial on how to create one.
If you have been thinking of a rich text field as its own control (like the <textarea> element), then you are thinking about it all wrong. Instead, think of the text field as being its own web page. It makes sense, doesn’t it? You’re applying HTML formatting to the text, after all.
The Structure
The text field itself is an <iframe> element, which (quite conveniently) comes with a JavaScript function called execCommand(). This function will become your colleague and your confidant. Your most trusted ally, and your most intimate friend.
To start off, create a new page with an iframe, a regular button, a submit button, and a hidden text field. The regular button will toggle the bold setting of any selected text within the iframe. The submit button is there for decoration only, and as a reminder that sometimes a form will need to be submitted. As such, the iframe cannot be used as a form input field; instead, we will use the hidden text field to store the HTML code of the iframe element. Its contents will be updated upon submitting the form, as we will see later.
<html>
<head>
<title>Rich Text Editor</title>
</head>
<body>
<form method="post" name="myform">
<input type="button" onclick="formatText('bold')" value="Bold" /><br/>
<iframe id="textbox" style="width: 300px; height: 150px"></iframe><br/>
<input type="submit" value="Submit" />
<input type="hidden" id="text" name="text" />
</form>
</body>
/html>
The Backbone
The formatText() function, called by clicking the “Bold” button, is defined below. You can either save it in an external .js file and call it from the HTML page, or add it to the <head> section.
var objEditor; // Globally define the text box object
unction formatText(action) {
objEditor.execCommand(action, false, null);
}
window.onload = function() {
objEditor = document.getElementById('textbox').contentWindow.document;
objEditor.designMode = 'on';
document.myform.onsubmit = function() {
document.getElementById('text').value = objEditor.body.innerHTML;
}
}
As you can see above, the text editor object (with the ID “textbox”) is set to a global variable, which can then be called by any other functions. The formatText() function calls the omnipotent execCommand() function, which applies only to the <iframe> object and is extremely powerful. There is a complete list of commands below. The command used above is the “bold” command. The second argument determines whether a user interface is displayed. Since this is not needed, it is set to false. The third argument is the value of the command. Since we are toggling the “bold” setting, we set this to null.
Next, we define what will happen when the page loads by setting the document’s onload event handler to do a few things. First, the text editor object variable is set to the object itself. Next, the text editor iframe’s designMode setting is turned on; this makes it so that the HTML within the iframe is editable. This is a huge deal, because this is essentially what turns the iframe into a rich text field.
(Actually, you can even set the entire document’s designMode variable to “on”, rendering the entire document editable. Just imagine the possibilities!)
Finally, we set it so that when the user submits the form, it sets the “text” hidden field’s value to the HTML of the iframe.
The Commands
The following commands are some of the simpler commands that can be used: Bold (<b></b>), Italic (<i></i>), Underline (<u></u>), StrikeThrough (<s></s>), SuperScript (<sup></sup>), SubScript (<sub></sub>), Cut, Copy, Paste, Undo, Redo, InsertOrderedList (<ol></ol>), InsertUnorderedList (<ul></ul>), Outdent, Indent, JustifyLeft, JustifyCenter, JustifyRight, and JustifyFull.
SuperScript and SubScript raise or lower text, for things such as mathematic variables (like 72 and H2O). The commands Cut, Copy, Paste, Undo and Redo function the same way they do in word processors. InsertOrderedList inserts a numbered (ordered) list, while InsertUnorderedList inserts a bulleted (unordered) list. Outdent moves a paragraph of text to the left, while Indent moves it inward (to the right). The Justify commands align the text to the direction specified.
Change Font Size
The FontSize command changes the size of the selected text in the iframe, and requires a value from 1 to 7, 1 being the smallest size, 7 being quite large. This command is based on the soon-to-be obsolete <font> tag, which uses the same values for its size attribute.
This function is best used with a drop-down list whose onchange event handler calls a custom function that changes the font size to the selected value. To most accurately show the user what the end result would be, each line should resemble the following.
<option value="X"><font size="X">X</font></option>
Each item’s value is the size number, while the item is shown in that size, displaying the size number.
Change Font Name
There is a certain list of fonts that is safe to assume all users have installed on their systems. Known as the Core Fonts, these include Andale Mono, Arial, Comic Sans MS, Courier New, Georgia, Impact, Times New Roman, Trebuchet MS, Verdana, and Webdings. It is also safe to include a few fonts that are on most users’ systems, but not all: Arial Black, Lucida Console, Lucida Sans Unicode, Tahoma, and Wingdings.
Like we did with the font sizes, if we had a drop-down list of fonts, each displayed in its own font, we could then set the list’s onchange event handler to call up the FontName command, like so:
objEditor.execCommand("FontName", false, "Times New Roman");
It’s pretty straightforward how it works.
Further Inspiration
There are so many possibilities, especially with the sheer number of commands available at your disposal. For example, there is the 2D-Position command, which allows absolutely positioned elements to be moved by dragging. There is also the CreateLink, which adds a hyperlink or changes text into a hyperlink. InsertButton, InsertImage and
SaveAs are just a microscopically small selection of commands also at your disposal. For a full list of commands available, check out http://msdn2.microsoft.com/en-us/library/ms533049(VS.85).aspx.
No comments yet.