How to build a rich text editor for your web sites

This is a basic tutorial on how to build a basic javascript editor, fora more advenced one try here http://melomind-tutorials.blogspot.com/2009/09/how-to-use-ajax.html
Lets start with a nice not very technical tutorial, one that I find really fun, How to build a rich text editor for the web
All the code here will be browser compatible.
The Rich text editors (RTE) for the web are build with iframes, this is how:
The javascript responsable of turning an iframe editable is:
document.getElementById('your iframe id').contentWindow.document.designMode="on";
the code now looks like:

<script>
function activate_iframe(){
document.getElementById('iView').contentWindow.document.designMode="on";
}
</script>
<body onload=activate_iframe()>
<iframe id='iView'></iframe>
</body>

The next step is to integrate the basic option for the editor, bold, italic, underlined for the text in the editor:
For that we are going to use the built in execcommade function like this:
document.getElementById('iView').contentWindow.document.execCommand('bold', true, null); 

The above javascript we will become:

<script>
function activate_iframe(){
document.getElementById('iView').contentWindow.document.designMode="on";
}
function format_text(type){
document.getElementById('iView').contentWindow.document.execCommand(type, false, null); 
}
</script>
<body onload=activate_iframe()>
<iframe id='iView'></iframe>
<input onclick=format_text('bold') id="Button1" type="button" value="button" />
<input onclick=format_text('italic') id="Button2" type="button" value="button" />
<input onclick=format_text('underline') id="Button3" type="button" value="button" />
</body>

Ok good, now comes the part when we integrate the image insertion:
First there is the easy native way to do it:
document.getElementById('iView').contentWindow.document.execCommand(insertImage, false, "image source here");
But you can only insert an image with this function,you can not add or specify other attributes than the source (src=...), I will go throught these once done with the basics.

No comments:

Post a Comment