If you have ever used Hotmail’s Rich Text Editor and wondered how they do it, then this article will shed some light on that. Using IE5+ IFrame one can easily create an online content editor. Without the need of applets or ActiveX, I will show you how to set it up and how to extend this simple model with just some HTML and Javascript. We will see how to create toolbars that control your IFrame, like making something bold or italics. Then I’ll show you some ASP code that captures what you create and saves it as HTML code that you can then use to create HTML files or store it in your database.

Reference should be made to the following articles, since they are used in my code:

The final code in the download creates something to this effect:

What is an IFrame?

The IFrame works mainly like a regular frame. The main difference is that you can embed it within your page, thus creating inline floating frames. The main idea behind getting the IFrame to work like a content editor, is to create some buttons on your page that when clicked send Javascript commands to the IFrame. You can read the reference for the D/HTML if you like to get a better understanding of the API model. Pay special attention to the Command Identifiers and the DHTML Methods, as they are the main ones that are used for this exercise.

To create an IFrame, simply add this to your HTML code:

<iframe id="idContent" width="600" height="280"></iframe>

The IFrame can be declared with certain properties. Width and height are obvious ones. Assigning it an ID (idContent) makes it possible to call it from our Javascript.

IFrame innerworkings

To enable our IFrame to process Rich Text we first add some Javascript to our HTML that executes as the page loads.

var isHTMLMode = false
	function document.onreadystatechange() {
		idContent.document.designMode = "On";
}

Using DHTML’s innerText and innerHTML, we can switch between HTML and Text modes. So, we keep a variable called isHTMLMode which remembers what mode we are in. Actions can be sent to the IFrame only if we are in Text mode. Therefore, as the page loads, I set this to False by default. If you want to show off your skills in HTML, and you prefer to type source code straight into the IFrame, you can easily do so by switching modes. You might even want to copy and paste the source code from another page you created in Macromedia Dreamweaver or some other HTML tool. To automate the process of switching back and forth at your whim, we can create a Javascript function that does that for us.

function setMode(bMode) {
	var sTmp;
	isHTMLMode = bMode;
	if (isHTMLMode) {
		sTmp = idContent.document.body.innerHTML;
		idContent.document.body.innerText = sTmp;
	} else {
		sTmp = idContent.document.body.innerText;
		idContent.document.body.innerHTML = sTmp;
	}
	idContent.focus();
}

We can call this function through a checkbox. Checking it will move us to HTML mode, and unchecking it will take us back to Text mode.

<input type="checkbox" onclick="setMode(this.checked)">

Passing DHTML to the IFrame

Now that we have set up the IFrame and the HTML/Text modes, we need to be able to send DHTML commands to it, so that we can do cool stuff like making something bold or italics, etc. One of the most important methods of the DHTML model that we will be using is the execCommand. This method accepts 3 arguments:

execCommand(sCommand [, bUserInterface] [, vValue])
sCommand Required
String that specifies the command to execute. This command can be any of the command identifiers that can be executed in script.
bUserInterface Optional
Boolean that specifies one of the following values.
false Default. Does not display a user interface.
true Displays a user interface, if the command supports one.
vValue Optional
Variant that specifies the string, number, or other value to assign. Possible values depend on sCommand.

Since we are not going to use the second argument, let’s create our own function to exclude that:

function cmdExec(cmd,opt) {
	if (isHTMLMode) {
		alert("Please uncheck 'Edit HTML'");
		return;
	}
	idContent.document.execCommand(cmd,"",opt);
	idContent.focus();
}

Remember that idContent is the ID we gave to our IFrame. Let’s now show how to make something bold. First you create an object on your page, either text or image or anything else that you prefer, and add an onClick command that sends a method to the IFrame.

<img alt="ForeColor" src="images/editor/fgcolor.gif" onClick="foreColor()">

Any of the listed Command Identifiers in the Reference can be passed like above. However, execCommand is not the only method available to us. You can always use any of the other methods provided by the DHTML API model. But the real power comes from combining DHTML actions with your ASP code.

Creating your own Actions

Let’s create some actions to demonstrate. For starters, let’s say you want to provide a way for someone to highlight some text and set a color on it. First you create the action for it:

<img src="images/editor/Bold.gif" alt="Bold" onClick="cmdExec('bold')">

And then the function that it calls:

function foreColor() {
var arr = showModalDialog("selcolor.asp","", _
"font-family:Verdana; font-size:12; dialogWidth:45em; dialogHeight:24em" );
if (arr != null) cmdExec("ForeColor",arr);
}

The showModalDialog returns a single value back to the window where it originated from. Notice that I am calling a page called selcolor.asp, which is a custom ASP page. That way you can create your web-safe color palette to choose from.

Let’s do another example. Let’s say this time you would like your users to insert an image from a library of images that lives on your server. An example of this is to let people choose an emoticon (e.g. a smiley face). First, the action:

<img src="images/editor/imageLocal.gif" alt="Insert Local Image" onClick="insertImageLocal()">

And the function that it calls:

function insertImageLocal() {
	if (isHTMLMode) {
		alert("Please uncheck 'Edit HTML'");
	return;
	}
	var sImgSrc = showModalDialog("selectImage.asp","", "dialogHeight: 500px; dialogWidth: 400px; dialogTop: px; dialogLeft: px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;");
	if(sImgSrc!=null) cmdExec("InsertImage",sImgSrc);
}

The selectImage.asp can be some ASP code that displays a library of images. It could for example, loop through the contents of a folder on your site via the FileSystemObject (FSO), or it could be a query against a database. In the downloadable zip file of this article, I have an example that loops through a folder using FSO.

Saving your created content

<form name="editor" method="post" action="submit_editor.asp">
<input name="YOUR_CONTENT" type="hidden" value="">
<input type="button" name="Submit" value="Submit &raquo;" onclick="SubmitContent();">
</form>

We create a button that runs the Javascript function responsible for saving and posting our content. We declare a hidden field to capture our content and we leave it empty at creation. We wrap everything with a <FORM> that posts to an ASP page. Our button calls the function SubmitContent when clicked.

function SubmitContent() {
	if (isHTMLMode) {
		alert("Please uncheck 'Edit HTML'");
		return (false);
	}
	document.editor.YOUR_CONTENT.value = idContent.document.body.innerHTML;
	document.editor.submit();
}

Notice that we are capturing the HTML source of the IFrame content and pasing it to our local variable. and not the Text. We then submit the form, which should now become obvious that this is a simple POST of a variable called YOUR_CONTENT to the asp page submit_editor.asp. In submit_editor.asp, we can simply get that variable and work with it as we please (e.g. display it properly or put it in a database field).

<%
Dim strContent
strContent = Request.Form("YOUR_CONTENT")
'write HTML source
Replace(Server.HTMLEncode(strContent), vbcrlf, "<br>")
'or simply render it on the browser
Response.Write(strContent)
%>

Editing your created content

If you save your created content to a file or a database field or in some other format, you may want to edit it. How do you do that, so IFrame can pull up your saved content and populate itself with it? By simply adding a source declaration to your IFrame HTML code. Assume that you saved your content to a database field. The row is defined by a unique identifier ID. Edit your code to something like this:

<%
Dim numID
numID = Request.QueryString("ID")
%>
<iframe width="600" height="280" id="idContent" src="getContent.asp?ID=<%=numID%>"></iframe>

This way you can pass the ID of the row you want to edit to the page where you have your IFrame. The getContent.asp page of the source is your custom ASP code that looks up the database and returns the content. To make it return properly you do a Response.Write in that page:

<%Option Explicit%>
<%
Dim numID 'unique identifier passed through the IFrame
Dim strContent 'returned HTML source from database
numID = Request.QueryString("ID")
If numID <> "" Then
'	do your database query and populate strContent
	Response.Write(strContent)
End If
%>

While requiring the use of IE5+ for this to work, for those projects where this is possible, IFrame provides us with a neat way of creating a web-based content editor. Real power comes from customizing the interface to meet your needs. You will soon notice that the HTML code that IFrame generates is by far not browser compatible, but again works fine with IE5+ and for the most part with NS6+.

3 Responses to Web-based Content Editor using IFrame

  • Ankur

    i need codes in php for my college project

  • David

    Really enjoyed working my way through this. Can’t work out why the part below is creating a syntax error though. Am I just being dumb?

    function document.onreadystatechange() {
    idContent.document.designMode = “On”;
    }

    • Evagoras Charalambous

      @David,

      A bit late to the party, but have you tried something like this instead:

      document.onreadystatechange = function () {
           idContent.document.designMode = “On”;
      }

Leave a Reply

Your email address will not be published. Required fields are marked *