Oleg Terenchuk (litwol) and I were discussing the Rich Text Editor (RTE) in core thread on the developer’s list the other day. He has a great idea to create some hooks to allow this to be simple, powerful, and easily extendible. It would be written in jQuery, and allow buttons to be built on top of it.
The difficult part would be getting jQuery to recognize selected text in a textarea. jQuery has no native functions to do this, so a plugin would have to be written. Most current jQuery RTE’s work using an IFrame, due mainly to the difficulty in getting FireFox to easily query the selected text of a textarea.
In Internet Explorer, it’s easy: built-in proprietary properties, .selectionStart and .selectionEnd, will give you whatever’s selected, whether in a textarea, or in the document itself. Of course, it’s non-standard, so it doesn’t work in FireFox.
I found the solution while we were chatting. However, it is in javascript, rather than jQuery, which means we have to do some tweaking. Using the original post for inspiration, ideally we could code something like this:
jQuery.fn.selectionText = function() {
if (this[0].selection) {
return this[0].selection.createRange().text;
}
else if (this[0].selectionStart != ‘undefined’) {
return this[0].value.substring(this[0].selectionStart, this[0].selectionEnd);
}
}
Unfortunately, I don’t believe that this[0].selection will work, from what I’ve read. Thus, we have to use document.selection, which will work after a fashion. Unfortunately, that will select text from anywhere on the page, so we’ll have to do some more research.
If it works, however, this should give the text of the selection. This would have to be tweaked to work with elements other than ID’s, as jQuery $(‘.whatever’) actually returns an array of elements. This code would only return the selected text of the first element, which might be blank if the selection is elsewhere.
Then we could do something like:
jQuery.fn.setSelectionText = function(txt) {
if (this[0].selection) {
this[0].selection.createRange().text = txt;
}
else {
this[0].value = txt;
}
this[0].focus();
}
You would use this something like this, attaching this to a button, say, that makes something bold:
$(document).ready(function() {
$(‘#bold-button’).click(function() {
$(‘#my-textarea’).setSelectionText(‘‘ + $(‘#my-textarea’).selectionText() + ‘‘);
});
});
That should do it. We’ll be building and testing later this week, so expect a live demonstration soon!