Click here to Skip to main content
15,891,375 members
Articles / Programming Languages / Javascript
Article

Yahoo! mail and Hotmail like Rich Text Editor

Rate me:
Please Sign up or sign in to vote.
4.60/5 (67 votes)
28 Feb 2002 625.5K   6.9K   121   219
Yahoo! mail and Hotmail like Rich Text Editor using Scriptlets

Sample Image - richtext.gif

Introduction

A friend asked me an interesting question related with a Rich Text Editor Control using JavaScript . At first, I felt to have some study before I answer him. I knew this is tough to answer but thought there is some ways to get solve it. After a long surfing fortunately, found a small secret features of IE known as "scriptlet".

Scriptlet

For many web programmers Scriptlet is still a mystery. Although this features was introduced in IE 4.0 and never used highly. I think its due to cross-compatibility issue because Netscape doesn't support it but don't worry Microsoft has submitted Scriptlet to W3 long ago.

Let me introduce Scriptlet with some few examples. Probably from a year long you are using a rich text compose box in Yahoo! mail or hotmail and someone who are little crazy about internal, probably gone through every tags to know what exactly is this? ... but got nothing except <object ..> tag that is usually use to invoke COM . I have seen lots of programmer used to consider the yahoo! or hotmail compose box as COM /ActiveX ! . Indeed it looks like COM when it loads first but actually its not that what you think.

Actually Scriptlet is ActiveX script. This components consisting of Plain text script code instead of binary. It is nothing more than an HTML file with a body and some script code. It is simply a HTML file that can be nested inside another HTML page like you use to include(...) a file using server side scripts.

The way of executing the Scriptlet is similar to applet or ActiveX. Both ActiveX and Scriplet expose properties, events and methods and also can driven via automation. Well, If you try it once with your web projects, you will find the importance of such tools. Overall I prefer to put it in "easy to adopt" categories. It is the only one tool known to be the coolest solution for DHTML code reusability. Remember It is included in same object tag where we use to invoke ActiveX components.

HTML
<object type="text/x-scriptlet"
data= "Scriptlet.html"></object>

But There are a number of fundamental differences between a standard ActiveX control and a scriptlet

  • It is identified by name, not with an long 128-bit CLSID.
  • It is invoked direct from the server not from the client PC. So no need to compile, register like you do with your ActiveX DLL components before using its various methods, properties from the Web pages.

Here is a very simple example that demonstrate the real usage of scriptlet. The example shows a simple non-toolbar Rich Text Editor.

Before we get inside the example lets read few essential stuffs behind a Web Based Rich Text Editor. In our example IFRAME (Inline Frame) is interfaced as Editor.

IFRAME

IE (3 or later) has introduced the concept of floating frames. These are much like standard frames, except they can be anywhere within a standard HTML document. A floating frame must be enclosed within

<iframe> ...
       </iframe>
elements. like this.

HTML
<iframe class="mytext" width="100%" ID="mytext" height="200">
</iframe>

Every IFRAME element in a document is an object that can be manipulated through scripting. By using the several methods and properties of IFRAME object we can do anything we like.

At frist when u including <iframe..> in the document you can't input or type anything you want. To make it work you need to set the designMode="On" for example.

JavaScript
myiframe.document.designMode="On";

To start writing in IFRAME you have to call open,write and close properly. like this.

JavaScript
myiframe.document.open();
mytext.document.write("Test");
myiframe.document.close();

There are more than 40 methods and several properties in IFRAME. For more information you can visit at Microsoft.

IFRAME Properties

className, document, id, innerHTML, innerText, isTextEdit, lang, language,
offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth, outerHTML,
outerText, parentElement, parentTextEdit, sourceIndex, style, tagName, title,
align, border, borderColor, dataFld, dataSrc, frameBorder, height, hspace,
scrolling, src, vspace
and width. etc.

IFRAME Methods

We are looking at few methods that is used in our examples. execCommand, contains, getAttribute, insertAdjacentHTML, insertAdjacentText, removeAttribute, scrollIntoView and setAttribute, focus etc.

execCommand

Sets the given command to the text. Like bold, italic, underline, justifyleft, justifycenter, justifyright etc. like

JavaScript
myiframe.document.execCommand("bold");

contains

Checks whether the given element is contained within the object.

getAttribute

Retrieves the value of the specified attribute.

insertAdjacentHTML

Inserts the given HTML text into the element at the location.

scrollIntoView

Causes the object to scroll into view, aligning it either at the top or bottom of the window.

removeAttribute

Removes the given attribute from the object.

setAttribute

Sets the value of the specified attribute.

focus

Causes the element to receive the focus and executes the code specified by the

onfocus
event.

Example Time to see the real example of Scriptlet. This file (main.htm) includes "richtext.htm" in its <object..> tag. File: main.htm

HTML
<html>
<head></head>
<body>
<h2>I am main page that execute scriptlet</h2>
<object type="text/x-scriptlet" data= "richtext.htm"></object>
</body>
</html>
Lets use some important method and develop our own Rich text editor.
HTML
<!-- File: "richtext.htm" -->

<html>
<head>
</head>
<body>
<form>
    <input type=checkbox name=source value=1 OnClick="SourceCode(source.checked)">Source
    <input type=checkbox name=bold value=1 OnClick="RichtText('Bold')"><b>B</b>
    <input type=checkbox name=under value=1 OnClick="RichtText('underline')"><u>U</u>
    <input type=checkbox name=italic value=1 OnClick="RichtText('italic')"><i>I</i>

    <select name=align OnChange="RichAlign(this[this.selectedIndex].value)">
        <option value="justifyleft" selected>Left</option>
        <option value="justifycenter">Center</option>
        <option value="justifyright">Right</option>
    </select>
    
    <iframe class="mytext" width="100%" ID="mytext" height="200">
    </iframe>
    
    <script langauge="JavaScript">
        function RichtText(what) {
            mytext.document.execCommand(what);
            mytext.focus();
        }

        function RichAlign(what) {
            mytext.document.execCommand(what);
            mytext.focus();
        }

        function SourceCode(mode)
        {
            var htmtext;
            if(mode) {
                htmtext=mytext.document.body.innerHTML;
                mytext.document.body.innerText=htmtext;
            }
            else {
                htmtext=mytext.document.body.innerText;
                mytext.document.body.innerHTML=htmtext;
            }

        }    

        var bLoad=false
        var pureText=true
        var bodyTag="<body MONOSPACE STYLE=\"font:10pt arial,sans-serif\">"
        var bTextMode=false
        mytext.document.open();
        mytext.document.write(bodyTag);
        mytext.document.close();
        mytext.document.designMode="On";
    </script>
</form>

</body>
</html>

open main.htm. Isn't it cool?

F.A.Q

How to submit the text in the iframe to another page?

"d-lay" response is as follow.
It isn't possible to read from the IFrame as a form object, however you can use javascript to copy the text from the IFrame into a hidden field in your form and then submit.

Here's the function I added to allow you to do this

JavaScript
function savedocument() { // added 16-02-02 "D-Lay!" <webmaster@7thportal.org> 
  if (!isRTextMode()) return;
  setMode(1); //switch doc to html mode for save
  document.saveform.msg.value=mytext.document.body.innerText;
  setMode(0); //switch doc back to text mode
  document.saveform.submit(); // submit form for save
}

Wondering how can i put a default value or string into the text box?

See below. You have to change either var bodyTag or mytext.document.write(..). That's it!

JavaScript
var bLoad=false
var pureText=true

/** Default value here **/
var bodyTag="<body MONOSPACE bgcolor=green " +
            "STYLE=\"font:10pt arial,sans-serif\">My Text is here"

var bTextMode=false
mytext.document.open();
mytext.document.write(bodyTag);
mytext.document.close();
mytext.document.designMode="On";

Conclusion

I hope you've found this article interesting. This features is remarkably easy to use especially for DHTML code reusability. Being an ActiveX script, It can solve several problems. For demonstration, I tried Rich Text Editor. I encourage everyone to try it and send me some comments.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: Copy and paste by right click? Pin
LVT14-Mar-04 23:23
LVT14-Mar-04 23:23 
GeneralIFrame Pin
Anonymous8-Apr-03 10:08
Anonymous8-Apr-03 10:08 
GeneralRe: IFrame Pin
Anonymous6-Dec-03 23:39
Anonymous6-Dec-03 23:39 
GeneralStyle sheet Pin
leewsimpson24-Mar-03 4:44
leewsimpson24-Mar-03 4:44 
GeneralInvalid Links Pin
david.hughes27-Feb-03 21:56
david.hughes27-Feb-03 21:56 
GeneralRe: Invalid Links Pin
juan954923-Jul-03 22:35
juan954923-Jul-03 22:35 
GeneralSkip the Servlet Entirely Pin
Anonymous20-Feb-03 10:48
Anonymous20-Feb-03 10:48 
GeneralHowTo Really Set and Submit the HTML Pin
Moe Cazzell19-Feb-03 9:14
Moe Cazzell19-Feb-03 9:14 
Using the code from w3richtechedit_src.zip offered for download,
in your Test Page (the zip's index.htm), insert (before any form):


<script>
<!--

// The HTML on the page is accessed by the html property of the scriptlet
// created by the javascript used by the Editor Scriptlet.

// In order to access this property,
// you will need to assign an ID to the scriptlet object on the Test Page
// (something the original code neglected to do).

// For example, I assigned an ID of "editor"
// to Editor Scriptlet object on my Test Page.
// Thus, I can access the html by using editor.html


// Setting the Default Html

function document.onreadystatechange() {

// We cannot safely access the object's methods or properties
// until the document is 'complete'.
// So, we must use the onreadystatechange event handler
// and check the document.readyState property.
// The event is triggered several times,
// but is is only triggered once with the readyState set to 'complete'.

if (document.readyState == 'complete') {
editor.html = '<P><STRONG>Start Here:</STRONG></P>';
editor.CompFocus(); // as defined by the Editor Scriptlet

// Or, if you already have onreadystatechange event handler,
// modify it by adding this code.
// But make sure that this code only executes after
// document.readyState == 'complete'
}
}


// Accessing/Submitting the HTML

function SubmitEditor() {

// How quickly is a button available in a multitasking environment?
// First check the document state to be safe:
if (document.readyState != 'complete') {
alert('The page has not yet finished loading.\r\n'+
'Wait a couple of seconds and try again.');
return false; // the false is only useful if put in onsubmit
}

// For quick testing, I use the alert below
// and I added a button to the Test Page to call this function.

alert(editor.html);

// On your Test Page, you might create a form on the page
// with a INPUT element of type HIDDEN
// and set that element's value property to editor.html
// for example, I might call the form name "MyForm"
// and the hidden value, "MyHiddenHtml" .. Then:

// document.MyForm.MyHiddenHtml.value = editor.html

// You want to do this either in the Form's onsubmit event, if any,
// or otherwise before calling document.MyForm.submit()
// Note: the submit method does NOT call the form's onsubmit event

// if inside onsubmit, don't forget to return true;
}
// -->
</script>


Also add to your Test Page (the zip's index.htm): your test form and it's call to SubmitEditor, or a test button like mine below.

Below, I show how to set the ID of the object to "editor" (and a fix for the original's bogus height value), and a how to add a test button to the page:


<p><object id="editor" data="main.htm" align="baseline" border="0" width="500" height="256" type="text/x-scriptlet"></object></p>

<p><button type=button onclick="SubmitEditor()">Submit HTML</button></p>


Ignore the Bogus FAQ in the article and the various ignorant attempts to make that work with the completely different code in the zip. Take a careful look at the compose.js in the zip.. UGH! it needs a lot of work.

To compare, try signing up with Yahoo and looking at its current editor for email (under the Color and Graphics link).
GeneralRe: HowTo Really Set and Submit the HTML Pin
Anonymous19-Feb-03 12:58
Anonymous19-Feb-03 12:58 
GeneralRe: HowTo Really Set and Submit the HTML Pin
anonymous coward31-Mar-03 9:45
anonymous coward31-Mar-03 9:45 
GeneralIframe - Problem Pin
Gulbarga4-Feb-03 19:54
Gulbarga4-Feb-03 19:54 
GeneralRe: Iframe - Problem Pin
Moe Cazzell19-Feb-03 9:32
Moe Cazzell19-Feb-03 9:32 
GeneralTo find out the cSS Style in the iFrame above.. Pin
Anonymous13-Jan-03 22:27
Anonymous13-Jan-03 22:27 
GeneralRe: To find out the cSS Style in the iFrame above.. Pin
Moe Cazzell25-Feb-03 10:37
Moe Cazzell25-Feb-03 10:37 
Generaliframe under security - get rid of browser alert message Pin
raphi9-Jan-03 3:55
raphi9-Jan-03 3:55 
GeneralRe: iframe under security - get rid of browser alert message Pin
Anonymous16-Mar-03 10:24
Anonymous16-Mar-03 10:24 
GeneralA little help please... Pin
Dustpup4-Jan-03 17:17
Dustpup4-Jan-03 17:17 
GeneralRe: A little help please... Pin
Dustpup4-Jan-03 18:35
Dustpup4-Jan-03 18:35 
GeneralTutorial Pin
slin4-Dec-02 6:25
slin4-Dec-02 6:25 
GeneralRe: Tutorial Pin
Steve McLenithan20-Dec-02 2:54
Steve McLenithan20-Dec-02 2:54 
GeneralSaving value from this editor Pin
AYSHA SAEED3-Dec-02 17:40
AYSHA SAEED3-Dec-02 17:40 
GeneralRe: Saving value from this editor Pin
Steve McLenithan20-Dec-02 2:53
Steve McLenithan20-Dec-02 2:53 
Generalsubmit text in the Iframe to Another page Pin
Suresh_u_n28-Nov-02 3:18
Suresh_u_n28-Nov-02 3:18 
GeneralSorry, but I don't understand this... Pin
dbdownunder20-Mar-03 21:24
dbdownunder20-Mar-03 21:24 
GeneralAddin Story Title and Created By Field Pin
scottyunt8-Nov-02 7:50
scottyunt8-Nov-02 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.