It would be nice if we have a HTML text editor that doing a simple task of HTML editor for us. It works just like HTML view of WordPress admin page when we write a post. We select the text press specific button and then the selected text will be enclosed with appropriate format. I Test the code in Mozilla Firefox and Internet Explorer, so in both browsers this code should works fine. Here the screenshoots:
Screenshoots page.
We need to prepare the prerequisites.
As prerequisites, at least we need two things. First, we need to know how to define the cursor position inside a <textarea> element, second we need to know how to retrieve a selected text inside a <textarea> element. So, for the first step, I will talk about the both things shortly.
Every browser brings the different behaviour. The browser quirk will make our code a little bit longer because we need to specify different code for different browser. Defining cursor position (current position) is trivial in Mozilla Firefox, but we need a little trick in Internet Explorer. If we want to retrieve selected text in a <textarea> element, both (Forefox and IE) has their own way too.
Defining Cursor Position Inside a <textarea> Element
In Firefox we just need the following code to determine the current position of cursor in a <textarea> element:
var currentPosition = txtArea.selectionStart;
txtArea is a <textarea> element.
Internet Explorer (I use IE 6) doesn’t have selectionStart and selectionEnd property, so we need a little more effort to determine start and end position of the cursor (this is a tricky way).
var range = document.selection.createRange();
var drange = range.duplicate();
drange.moveToElementText(txtArea);
drange.setEndPoint("EndToEnd", range);
var currentPosition = drange.text.length - range.text.length;
var endPosition = drange.text.length - currentPosition;
Read the rest of this entry »