Rich Text Editor - Part II
 
Published: 27 Feb 2007
Abstract
After we have explored how to create a rich text editor, it is time to add some new features which will extend its usability and benefits. In this article we will get to know how new features were implemented. Again, all the major functionalities are written in javascript.
by Haissam Abdul Malak
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 34616/ 47

Introduction

After we have explored how to create a rich text editor, it is time to add some new features which will extend its usability and benefits. In this article we will get to know how new features were implemented. Again, all the major functionalities are written in javascript.

In the previous article you saw how easy it was to create your own text editor. Of course, as a first version the editor contained standard features. Now, after I had sometime to add new functionalities, I can say it contains more features and it is more robust.

Below are the newly added features.

1.    Strike Through: This will strike through the text entered by the user.

2.    Decrease-Increase Indent: This will decrease or increase the text indent.

3.    Insert Images: This will open a new window giving the user the ability to upload an image to the server and insert it directly into the editor.

4.    Copy, Cut, and Paste: This will copy, cut or paste the text entered by the user into the clipboard.

5.    Print: It allows only the text to be printed by opening the Print Setup dialog.

6.    Bulleted List & Numbered List: It adds a bullet or number at the beginning of the text.

7.    Super-Sub script: It will format the text into super script or sub script.

8.    Insert Lines: It adds lines to the text.

Add HTML code to the user control

In this section we will add new HTML elements to add more features into the toolbar. We will place images for all the above mentioned actions and handle all the events to perform their functionalities.

Listing 1

 
<IMG class=StrikeOut id=Strikethrough
 onmouseover="ChangeImg('Strikethrough','strikethrough.over.gif')"
 title="Strike Through" onclick="Formats('StrikeThrough','<%= this.HamEditorChildID %>' )"
 onmouseout="ReturnImg('Strikethrough','strikethrough.gif',imgStatusUnderLine)"
 src="Images/strikethrough.gif" >
 
 

In the above listing we added an img HTML control. The onmouseover event will call a javascript function (which I already explained in the previous article), will change the image to a selected one, the onclick event will call another function which will apply the formatting into the selected text, and onmouseout will return the image to its previous state. For the rest of the features we will use the same concept except for the Insert Images.

Please download the project to see exactly how we created all the HTML tags.

Figure 1

 

 

Javascript File

In this section we will add the new functions to the already created javascript file to handle the events for all the new features. They are all defined in one javascript file linked to this editor.

Listing 2

 
function Formats(style,editorId)
{
// Save the Iframe id
var finalDivId = editorId + '_content';
                  
// Set the focus back to the text
document.frames[finalDivId].focus();
                  
// Apply the new style
document.frames[finalDivId].document.execCommand(style);
                  
// Set the focus back to the text
document.frames[finalDivId].focus();
}

 

The above function is used by almost all the new event handlers. It takes two parameters; the first is the style to be applied, for example Copy, Paste, etc; the second is the editor id. We used the same function used before (execCommand) to apply the transformation.

 

Listing 3

function SetBorders(id)
{
// set the borders to the emoticons icons onmouseover
var imgBorder = document.getElementById(id);
imgBorder.style.borderStyle = "solid";
imgBorder.style.borderWidth = "thin";
imgBorder.style.borderColor = "#688B9A";
}

The above function is being called when the insert emoticons div layer is shown. When the mouse is over an emotion, what we do is call this function which will set the borders for the table cell. In this way, it will be obvious for the user to see that he is over a specific emoticon. Notice the x image we added, it allows the user to close the div layer if he does not want to add any emoticons.

Figure 2

Listing 4

function ClearBorders(id)
{
// Clear the borders of the emoticons icons onmouseout event
var imgBorder = document.getElementById(id);
imgBorder.style.borderStyle = "solid";
imgBorder.style.borderWidth = "thin";
imgBorder.style.borderColor = "white";
}

The above function will be called when the mouse is out of a specific emotion to clear its borders.

Listing 5

function SetImage(editorId,path,e)
{
// Get the click location
var height = e.clientY + parseInt('5');
// Get the height inside the clicked image
var offsetHeight = parseInt(e.offsetY);
height = height - offsetHeight;
                  
// Get the click location(width)
var width = e.clientX
// Get the width inside the clicked image
var offsetWidth = parseInt(e.offsetX);
width = width - offsetWidth;
                  
// Save the iframe id
var finalDivId = editorId + '_content';
path = unescape(path);
                        
// Insert an image from the users Computers. 
window.open('UploadImages.aspx?path=' + path +
 '&f=' + finalDivId,null,'width=500px,height=50px,titlebar=no,menubar=no,statusbar=no,toolbar=no,top='
 + height + 'left=' + width );             
                        
}

For the insert images new feature, we created a new webform called UploadImages.aspx. This form will be open when the user clicks on insert images icon to allow the user to select an image from his/her computer and upload it into the server in order to be able to insert it into the text editor. It contains two other fields to let the user specify the width and height of the image he/she wants to insert after it was uploaded. Below is a picture of the text editor when this new window is being opened.

Figure 3

The user has the ability to browse his/her computer to select an image and in its code behind and we are handling the upload part into the web server. I gave a great option for the administrator to set the directory on the web server where the image is going to be uploaded. I will explain it in detail in the code behind part. The maximum number of digits of the height and width properties is 3. The minimum value for the height property is 100 px and the maximum value of the width property is 150 px; as you can see they are their default values.

Listing 6

function insertsImage(imageurl,editorId,height,width)
{
opener.document.frames[editorId].focus();
            
if(imageurl != "" | editorId!= "")
{
imageurl = unescape(imageurl);
var imageurl = imageurl + '"'  + "width=" + width + "px" + " " + "height="+ height + "px";
  // Save the iframe id
opener.document.frames[editorId].document.execCommand('InsertImage',false,imageurl);
}
opener.document.frames[editorId].focus();
}

This function will be called when the user clicks on insert image. In its click event we are uploading the file and then inserting the image through javascript into the text editor with the specified width and height.

Figure 5

Code Behind

In this section we will see how the upload images code behind is implemented and how the administrator of this editor can set the default directory where the images can be uploaded.

 

Listing 7

public string FilePath
{
get
{
return _filePath;
}
set
{
_filePath = Server.HtmlEncode(Request.ApplicationPath + value);
}
}

The above listing is a property of type string which the administrator can use to set the default upload directory. The below listing will show you how to use it in your webform to specify the directory. This path will be sent to the UploadImages.aspx page query string when it is being opened from the javascript function.

 

Listing 8

string imagePath = "/UserImages";
((hamHtmlEditor)this.FindControl("HamHtmlEditor1")).FilePath = imagePath;

Listing 9

public string Location
{
get
{
return _location;
}
set
{
_location = value;
}
}

The above property is being used to get the editor ID in order to be able to insert it directly after being uploaded to the web server.

Listing 10

if(heightValidator.IsValid && widthValidator.IsValid)
{
string elementToInsert = Request.QueryString["f"];
if(UploadImage.PostedFile != null && UploadImage.PostedFile.ContentLength > 0)
{
try
{
string fileName = System.IO.Path.GetFileName(UploadImage.PostedFile.FileName);
string fileLocation = Request.QueryString["path"+ "/" + fileName; 
this.ImagePath = Server.HtmlEncode(fileLocation);
this.Location = elementToInsert;
Button1.Enabled = false;
UploadImage.PostedFile.SaveAs(Server.MapPath(fileLocation));
}
catch(Exception ex)
{
Response.Write("<script language=javascript>alert('"+
ex.Message.ToString().Replace(@"\",@"\\")+"');</script>");
}
finally
{
Button1.Enabled = true;
}
}
}

The above code is written inside the insert images' button click. Its purpose is to upload the image to the already specified directory after it checks if the height and width values are correct. The try and catch blocks are used to handle exceptions.

NOTE: One important thing Administrator has to note is he/she has to give writen permission to ASPNET user to access UserImages folder or to the folder path which is in the imagePath variable. This change is needed to write/upload an image to the desired folder.

Listing11

public bool ShowHeader
{
get
{
return _Header;
}
set
{
_Header = value;
}
}

A new property of type Boolean is introduced. Once it is set to false the toolbar will not show up. I added this property to give you the ability to show only read-only text after the text is being posted.

Figure 6

The above figure is the rich text editor when its ShowHeader property is set to false. The toolbar and the below other icons will be invisible. In this way, you can use it only for displaying your saved text.

Figure 7

Here is a final version of the editor with all the new features being used.

Conclusion

This editor is being tested on IE only for this release. The next release I will work on making it workable on multiple browsers. Once again, your ideas are welcome to enhance this editor or to report any bug. I will try to make it as a custom control which will be easier for you to use in the future. Hope you gained useful information throughout this article.

Source code of the Article

Happy Coding!



User Comments

Title: add more function with html editor   
Name: sahir saiyed
Date: 2010-10-19 2:33:52 AM
Comment:
thank for this tutorial i want to add language converter with html editor like english to hindi converter as drop down menu
please help me
Title: template feaure in the editor   
Name: SVK
Date: 2010-08-13 7:32:23 AM
Comment:
this is a good editor which can be easily implemented in asp.net web application, but iculd we add a additional feature where by user can create a template & save it and insert it when needed
Title: VB equivalent   
Name: Etcitty
Date: 2010-03-19 3:41:48 PM
Comment:
((hamHtmlEditor)this.FindControl("HamHtmlEditor1")).FilePath = imagePath;

What is the VB equivalent of this code. Going in circles. Otherwise this soars.....
Title: please help me ...   
Name: deepak sharma
Date: 2009-12-23 1:16:56 AM
Comment:
i want to set some default text on page load please tell me how can i do with this rich text box..please.
Title: abt rich text box   
Name: deepak
Date: 2009-12-21 2:05:00 AM
Comment:
hello sir will u tell me how can i get text value in code behind..
Title: Improved Editor   
Name: Thomas
Date: 2009-03-31 6:31:32 PM
Comment:
This is very nice, but if you like a updated version go to:
http://www.codeproject.com/KB/scripting/editor.aspx
Title: using   
Name: dhirendra
Date: 2009-03-26 6:22:18 AM
Comment:
hello sir i face a problem i can get .dll(in bin folder) file of richtexteditor .plz givw me solution soon
Title: using   
Name: janardhan
Date: 2009-02-25 1:53:03 AM
Comment:
i have facing problem to utilise this editor in c#.net inline code
Title: Jazakumullah hu kairan kasira   
Name: Muhammed ismail
Date: 2009-01-07 4:26:38 AM
Comment:
Haissam Abdul Malak! Excellent work, May the Alimighty reward you with best on the doom. Your work has really solved my major issue in a project.

Warm regards and Duaa
Title: Freetutes   
Name: Ali Abbas
Date: 2008-12-30 1:07:42 AM
Comment:
Quite easy to understand and do it ourselves
Title: Saving Code   
Name: Divyesh Tandel
Date: 2008-10-14 2:56:24 AM
Comment:
hii author, i wanted to know how to save the contents we type in the rich text editor. can u give me the code for storing the contents typed in the rich text editor to the database using stored procedure.can u reply to this mail urgently.
Title: Cross Browser Editor   
Name: Haissam Abdul Malak
Date: 2007-10-02 12:45:29 PM
Comment:
Check the below link to get the latest version of this editor which works perfectly on FireFox and IE
http://dotnetslackers.com/community/blogs/haissam/archive/2007/10/02/rich-text-editor-works-on-ie-and-firefox.aspx

Regards,
Title: Hyper Link   
Name: JuanJo"
Date: 2007-09-29 4:01:37 PM
Comment:
Hi!
this is a very good Editor and also quiet simple to understand for beginners,...congratulations!
Now, I'd like to know how can I add an hyperlink option to text in this editor.
Can anyone help me please???????????
my mail is juanjo_dm7@yahoo.com
thnx
Title: format paragraph   
Name: melcom
Date: 2007-09-18 4:41:53 AM
Comment:
hi..

please help how to format paragraph? cause now the paragraph is to high...

thx
Title: how to create emoticon with string text   
Name: melcom
Date: 2007-09-17 12:40:29 AM
Comment:
Hi...
this is a great editor thank u for doing this

i wanna ask bout how to insert emoticon only by type a string text like ':-)' or ';-)', or ':-p' on textbox without click the image icon on toolbar?


thx
Title: how to get the preview   
Name: anupama
Date: 2007-08-29 2:49:33 AM
Comment:
hi Haissam

this editor code is realy helpful....thank u for this...

can u please tel me how can i get the preview of it in another textbox after a button click...

please help me im new to this...

reply ASAP...

thank you...
Title: How to set default text?   
Name: Ashutosh
Date: 2007-07-23 2:01:12 AM
Comment:
I wonder how to add some default text say - 'my text' in bold or any other format and yet allow user to begin editing it immidiately. can anyone help?
Title: Re:Multiple TextBoxs   
Name: Haissam Abdul Malak
Date: 2007-07-13 3:49:35 AM
Comment:
Kushal this is already a user control where you can place it more than one instance in a single page
for more information please read the first part of this editor
http://aspalliance.com/1092

Best Regards,
Title: Multiple TextBoxs   
Name: Kushal
Date: 2007-07-13 2:17:26 AM
Comment:
Can we make a user control for this textbox or may be some other trick by which it can be made possible that we can use this control "n" number of times in a page.

where "n" may be defined at runtime... :)
Title: How to add to asp.net 2 Project?   
Name: Jonathan Heweit
Date: 2007-05-31 6:32:49 PM
Comment:
Thanks a lot for this componente, is exactly what I need, can you show me how to add to an asp.net 2 project.

thanks again,
Title: urgent help help help pls.........   
Name: Saheel
Date: 2007-05-30 4:04:47 AM
Comment:
hi Haissam thanxs for this html editor first,
i am working on forums site where i used this html editor
in new forums its working very fine But when i want to use it on forums edit in this case it is retriving data through database but did not grant access for edit it cursor is not coming there for editing anything i used
..
If (_text <> String.Empty) Then
frameDiv.InnerText = _text
End If
Title: Re:not able to use with FireFox   
Name: Haissam Abdul Malak
Date: 2007-05-26 1:23:13 PM
Comment:
This Editor version is for IE browsers and does not support Firefox, i will work on the next version for enabling cross browsers.
Title: not able to use with FireFox   
Name: JaiPrakash
Date: 2007-05-26 9:23:19 AM
Comment:
Hi

Please tell me how can i able to use this editor with FireFox 2.0

Please reply urgently.
Title: can't use in FireFox 2.0   
Name: Jariaman Barus
Date: 2007-05-26 1:27:01 AM
Comment:
Why this editor can't be used in FireFox 2.0?
I tried to use it in IE 6.0, and works well, but in FireFox 2.0, it can not run well.
Could you explain it, please?

Best Regards,

Jariaman Barus
Title: Populate from database   
Name: mac
Date: 2007-05-10 11:55:16 AM
Comment:
How do i populate the rich text box from database. I am using following code but it is not showing up

((hamHtmlEditor)this.FindControl("HamHtmlEditor1")).ContentInnerHtml = String.Format("{0}",myReader[1]);
Title: ContentInnerHtml returning 'False'   
Name: BA
Date: 2007-04-20 5:44:01 PM
Comment:
Hi,
The editor is great!
I converted it to VB and removed the "emoticons" and "add image" portions. Everything else seems okay, except:
1. After clicking "Convert to HTML", the HTML div is not placed properly; it is displayed below the frame div
2. The ContentInnerHtml property is returning string value 'False' and not the HTML value
What am I missing?
Thanks!
Title: Thank you Hasan   
Name: Asad Raza
Date: 2007-04-12 8:56:47 AM
Comment:
IN His name the Lord of mercy and grace!

Salaam Hasan,

Thank you for your help, I try your suggestions, and will get back to you with whatever results.

Regards,
Asad.
Title: Re:Please Help   
Name: Haissam Abdul Malak
Date: 2007-04-06 11:38:41 AM
Comment:
2 properties (ContentText & ContentInnerHtml) are available for you to retrieve the text entered by the user. if you want to get the HTML of the user entered text use
string textEntered = ((hamHtmlEditor)this.FindControl("HamHtmlEditor1")).ContentInnerHtml;
Just remember you have to add ValidateRequest="False" in the page directive. if you just want the text without the formats use the ContentText property

Best Regards,
HC
Title: Please help   
Name: Asad Raza
Date: 2007-04-06 11:23:40 AM
Comment:
In His name,

Salaam Hasan,
Im working on an ASP project which requires a rich text editor in a form, I want to know how to save the edited contecnt in database using ASP and will the editing be reflected when I retrieve the text from database later?
Please help me,
May Allah bless you
Title: Re:reinventing the wheel   
Name: Haissam Abdul Malak
Date: 2007-03-22 3:18:31 PM
Comment:
Maybe you are right, there are some good text editors but the idea of the article, which you probably missed, is to give the readers specially the new developers an idea of how these editors are developed. Thank you for your comment.

Best Regards,
HC
Title: reinventing the wheel   
Name: jake h
Date: 2007-03-22 2:45:52 PM
Comment:
Instead of dumping your time and energy into something that has been done 100 times, how about you help out the development of some of the projects already made for this. The most notable one is FckEditor, the #1 javascript project on all of source forge. It supports ASP.NET, and a whole host of other languages, and they could use your help.

This just seems like a waste.
Title: Re:Spell check!   
Name: Haissam Abdul Malak
Date: 2007-03-21 8:40:42 AM
Comment:
I will consider adding a spell check soon when doing some updates on this editor.

Best Regards,
HC
Title: Spell check!   
Name: G
Date: 2007-03-20 10:44:39 AM
Comment:
How possible is it to integrate spell check?
Title: Re:More than one textbox on a page   
Name: Haissam Abdul Malak
Date: 2007-03-19 1:45:28 PM
Comment:
As you may realized this rich text editor is created as a user control. so it can be placed n-times on your webform

Best Regards,
Title: More than one textbox on a page   
Name: G
Date: 2007-03-19 12:58:45 PM
Comment:
Can you place more than one textbox on a page?
Title: Really Amazing   
Name: Kavitha
Date: 2007-03-19 2:37:08 AM
Comment:
Its working fine. thanks a lot.If it possible would i get code for inserting a table and hyperlink in richtext editor. If i can get this code, it will be helpfull a lot for me.

Thanks,
Kavitha.
Title: Re:Amazing   
Name: ha
Date: 2007-03-05 2:32:55 AM
Comment:
Download source code from below link
http://authors.aspalliance.com/HabdulMalak/1156.zip

Best Regards,
Title: Amazing...   
Name: AjayKumar
Date: 2007-03-05 1:54:10 AM
Comment:
hiit is looking good i need to download this editor how can i?
Title: Congratulations!   
Name: Bilal Haidar [MVP]
Date: 2007-02-27 5:10:51 AM
Comment:
I can see the editor is improving!! Owesome!

Best of luck,
Regards

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-23 7:09:57 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search