PDA

View Full Version : Adding text surrounding highlighted text



monaya
03-15-2010, 07:00 PM
How do you add particular text surrounding the text a user highlights.

Similar to how it's done in this form like if someone highlights


text

becomes ...


text

Nile
03-15-2010, 11:09 PM
function singleWrap(myField, myValue) {
var obj = document.getElementById(myField);
var start = obj.value.slice(0, obj.selectionStart);
var end = obj.value.slice(obj.selectionEnd, obj.value.length);
var text = start + myValue+' ' + end;
document.getElementById(myField).value = text;
}
function wrapHighlighted(myField, myValue){
var obj = document.getElementById(myField);
var start = obj.value.slice(0, obj.selectionStart);
var end = obj.value.slice(obj.selectionEnd, obj.value.length);
var middle = obj.value.substring(obj.selectionStart, obj.selectionEnd);
var text = start + '['+myValue+']' + middle + '[/'+myValue+'] ' + end;
document.getElementById(myField).value = text;
}

The singleWrap function is used for inserting smileys.
And the wrapHighlightedis used for wrapping 2 things around the highlighted.

Heres the bold tag in your case:


<button type="button" onclick="wrapHighlighted('textarea','b')">B</button>

And to make a smiley:


<button type="button" onclick="singleWrap('textarea',': )')">: )</button>

monaya
03-16-2010, 02:15 AM
This is great!

Is there a way to highlight the text and remove the tags as well like an undo.

Also, when you click the button, the button itself stays highlighted and selected. is there a way to remove the focus from the button after it's hit.

Nile
03-16-2010, 02:53 AM
Hmm for undo I don't know - maybe create a function that makes an array of every full textarea value... What do you mean the button stays highlighted?

monaya
03-16-2010, 03:25 AM
I mean the button has focus http://screencast.com/t/ZGNmZDFjZ

monaya
03-16-2010, 08:47 PM
I found out today this code doesnt work in IE8 (not sure about previous versions.).

I had mozilla in my home computer.

In IE, when the function executes it basically highlights ALL text in the textfield (not what you highlight), copies and pastes it again and then surrounds it with the tags.

Nile
03-19-2010, 11:44 AM
Hmm - I don't know why. Try searching around google for something like this.