AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1156&pId=-1
Rich Text Editor - Part II
page
by Haissam Abdul Malak
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 34611/ 48

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!


Product Spotlight
Product Spotlight 

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