Ok, I'm sure you've seen the boards that allow you to select a bit of text and then wrap it in bbcode by pressing a button.
(ours doesn't work that way
).
Well it's trivial to do it in IE but trying to make it moz compatable is a fucking pain. I finally figured out how to do this by searching the moz bugzilla list and incorporating some of the code used as an example in one of the bug fixes
Here's the library to manipulate text selections:
//--------------------------------------------
// MOZILLA TEXT SELECTION LIBRARY
//--------------------------------------------
function moz_getSelectionStart(element) {
var startpos = 0;
startpos = element.selectionStart;
return startpos;
}
function moz_getSelectionEnd(element) {
var endpos = 0;
endpos = element.selectionEnd;
return endpos;
}
function moz_setSelectionStart(element,newposition) {
element.selectionStart = newposition;
}
function moz_setSelectionEnd(element,newposition) {
element.selectionEnd = newposition;
}
function moz_setSelection(element,newstart,newend) {
setSelectionStart(element,newstart);
setSelectionEnd(element,newend);
}
// Inserts a string at a given position
function moz_stringInsert(DOMEle,newtext,newpos) {
DOMEle.value = DOMEle.value.slice(0,newpos) + newtext + DOMEle.value.slice(newpos);
}
and here's the code for actually inserting the tag:
function moz_markSelected(element,tag) {
var startTag = "[" + tag + "]";
var endTag = "[/" + tag + "]";
var firstPos = moz_getSelectionStart(element);
// we're inserting one at a time
var secondPos = moz_getSelectionEnd(element)+ startTag.length;
moz_stringInsert(element,startTag,firstPos);
moz_stringInsert(element,endTag,secondPos);
// reset focus... after the first tag and before the second
moz_setSelectionStart(element,firstPos + startTag.length);
moz_setSelectionEnd(element,secondPos);
element.focus();
}
obviously this only works for simple wrapper tags but it could be expanded for font-size, etc... tags as well.
Just thought I'd share since it drove me fucking crazy for a while


