Here are some functions I've been using, edited a bit from the script I found originally on Massless.org.
/* BBCode Functions */
// Borrowed from [url="http://massless.org/mozedit/"]http://massless.org/mozedit/[/url]
// Written by Chris Wetherell - [url="http://www.massless.org"]http://www.massless.org[/url] - chris [THE AT SIGN] massless.org
var mozWrap = function(txtarea, openTag, closeTag){
txtarea = document.getElementById(txtarea);
var selLength = txtarea.textLength;
var selStart = txtarea.selectionStart;
var selEnd = txtarea.selectionEnd;
if (selEnd == 1 || selEnd == 2) selEnd = selLength;
var s1 = (txtarea.value).substring(0, selStart);
var s2 = (txtarea.value).substring(selStart, selEnd)
var s3 = (txtarea.value).substring(selEnd, selLength);
txtarea.value = s1+openTag+s2+closeTag+s3;
}
var IEWrap = function(txtarea, openTag, closeTag){
strSelection = document.selection.createRange().text;
if(strSelection != '') document.selection.createRange().text = openTag + strSelection + closeTag;
else document.getElementById(txtarea).value += openTag + closeTag;
}
var wrapSelection = function(txtarea, openTag, closeTag){
if(document.all) IEWrap(txtarea, openTag, closeTag);
else if(document.getElementById) mozWrap(txtarea, openTag, closeTag);
document.getElementById(txtarea).focus();
return false;
}
var wrapSelectionWithLink = function(txtarea){
var my_link = prompt('Enter URL:', 'http://');
if(my_link == null) return false;
if(my_link.length < 6){
alert('This URL is not valid!');
return false;
}
return wrapSelection(txtarea, '[url="http://'+my_link+'"]', '[/url]');
}
Use like so.
<a onclick="wrapSelection('comment', '[b]', '[/b]');" title="Bold"><img src="images/bold.gif" alt="Bold" /></a> <a onclick="wrapSelectionWithLink('comment');" title="URL"><img src="/images/url.gif" alt="URL" /></a>
<br />
<textarea id="comment"></textarea>
The wrapSelectionWithLink() is mostly an example of how you can expand the code to have special conditions such as prompting the user before adding the tag.
This code is cross-browser complient by the way; thus the IEWrap() and mozWrap().
Edited by Demonslay, 05 September 2007 - 09:39 PM.