Forum Moderators: open
having a bit of difficulty with this one..
i have been a read through the quirksmode article on this topic - using window.getSelection - but as far as FF is concerned the text within a text area, doesnt seem to count as text that can be selected.. which is a bit of a bugger, as that is what i want to do.
IE is happy grabbing text from anywhere it seems with that function..
what i am really trying to do is to allow someone to select some text in a textarea, and wrap it with something.
any ideas?
any help, as ever, much appreciated.
nat
if (typeof(myArea.selectionStart) != "undefined") {
var begin = myArea.value.substr(0, myArea.selectionStart);
var selection = myArea.value.substr(myArea.selectionStart, myArea.selectionEnd - myArea.selectionStart);
var end = myArea.value.substr(myArea.selectionEnd);
myArea.value = begin + text1 + selection + text2 + end;
} text1 and tag2 could be tags like <b> and </b>, and myArea refers to the textarea.
function wrap(txta,x,y)
{
if(txta.selectionStart==undefined) return;
var chars = txta.value.split("");
chars.splice(txta.selectionStart,0,x);
chars.splice(txta.selectionEnd+1,0,y);
txta.value = chars.join("");
}
function addArticleCode(t){
//crappy browser sniffer
var isFF = false;
var textSelected = false;
if(navigator.userAgent.toLowerCase().indexOf("firefox") > 0){
isFF = true;
}
var myArea = document.getElementById("body");
var begin,selection,end;
if (isFF == true){
if (myArea.selectionStart!= undefined) {
begin = myArea.value.substr(0, myArea.selectionStart);
selection = myArea.value.substr(myArea.selectionStart, myArea.selectionEnd - myArea.selectionStart);
end = myArea.value.substr(myArea.selectionEnd);
if (selection.length > 0){
textSelected = true;
}
}
}else{
if (window.getSelection){
selection = window.getSelection();
}else if (document.getSelection){
selection = document.getSelection();
}else if (document.selection){
selection = document.selection.createRange().text;
}
var startPos = myArea.value.indexOf(selection);
if (startPos!= 0){
var endPos = myArea.value.indexOf(selection) + selection.length;
begin = myArea.value.substr(0,startPos);
end = myArea.value.substr(endPos, myArea.value.length);
textSelected = true;
}
}
if(textSelected == true){
switch (t){
case "code":
startTag = "[xcode]";
endTag = "[/xcode]\n";
break;case "bold":
startTag = "[xb]";
endTag = "[/xb]";
break;case "italics":
startTag = "[xi]";
endTag = "[/xi]";
break;case "link":
startTag = "[xlink url=#*$!#*$!]";
endTag = "[/xlink]";
break;
}
myArea.value = begin + startTag + selection + endTag + end;
myArea.focus();
}else{
alert("No text selected.\nNo tags added");
}
}