Attach Client Side Event to Ajax HtmlEditorExtender






4.90/5 (6 votes)
Struggling to attach a Client Side Event to AJAX HtmlEditorExtender? Apply the trick and enjoy.
Introduction
This is an awesome trick which will guide you to add any client side events to a Ajax HtmlEditorExtender
.
Background
While coming across one question on CodeProject, I tried to implement this and finally succeeded. Let me explain this to you all.
Using the Code
To add an AJAX HtmlEditorExtender
, you need to add the following code in aspx
page. Mark the TargetControlID="txtEditor"
in HtmlEditorExtender.
<asp:TextBox ID="txtEditor"
runat="server"
TextMode="MultiLine"
Height="600px"
Width="600px">
</asp:TextBox>
<asp:HtmlEditorExtender ID="htmlEditExtForTextBox"
TargetControlID="txtEditor"
runat="server">
</asp:HtmlEditorExtender>
Now let's analyze the HTML rendered in browser for this.
For TextBox txtEditor
The TextBox
txtEditor
is now hidden as we can see below display: none;
and visibility: hidden
are added to the Style
Attribute of TextBox
.
<textarea style="height: 600px; width: 600px; display: none;
visibility: hidden;" id="txtEditor" cols="20" rows="2" name="TextBox1"></textarea>
For AJAX HtmlEditorExtender
There are many divs
generated to facilitate the HTML Editor. But to achieve our task, let's just pull out the main div
(with the help of FireBug Inspect Element Feature in FireFox) inside which we enter the text.
<div id="txtEditor$HtmlEditorExtenderBehavior_ExtenderContentEditable" style="height: 80%; overflow: auto; clear: both;" class="ajax__html_editor_extender_texteditor">
</div>
So, What's Next ?
Now, it is just a matter of attaching any Client Side Event to this rendered div
described above. Let's try to attach KeyUp
Event.
To do that, we have to place the below script inside Body
tags. Putting this in Head
tag will not work, as the HtmlEditorExtender
is not loaded at that time.
<script type="text/javascript">
Sys.Application.add_load(function () {
// Get the Editor Div by Class Name.
var htmlEditorBox = $('.ajax__html_editor_extender_texteditor');
// Attach the keyup Client Side Event to the above div.
htmlEditorBox.keyup(function () {
alert(this.textContent);
});
});
</script>
The code is quite self explanatory. It gets that main Editor
div
by its class name. Then alerts its Text Content.
Points of Interest
- As we attach
keyUp
Event, we can attach any Event with theHtmlEditorExtender.
- Please don't forget to include the jQuery file inside head tags as we are using jQuery while attaching the Event. You can also directly include the below script to include the latest
jQuery
file.<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
History
- 30 December 2013 - First version submitted for approval