Javascript Text Wrapping Function

Javascript Text Wrapping Function

The function takes the selected text (in a textarea field), wraps it with the appropriate BBCode tag (set by the type variable) and inserts it back where it was. If no text is selected, then it simply appends a blank BBCode block to the bottom of the textarea. It could probably stand to be rewritten in jQuery, but I don’t have time right now.

function wrapText(type) {
	var textarea = document.forms.edit.elements.pcopy;
	var caretPos = textarea.selectionStart;
	var caretEnd = textarea.selectionEnd;
	var value = textarea.value;
 
	if (caretPos < caretEnd) {
		textarea.value = value.substring(0, caretPos) + //all the text before the selection
					'[' + type + ']' + //bbcode start
					  value.substring(caretPos, caretEnd) + //selected text
					'[/' + type + ']' + //bbcode end
					value.substring(caretEnd, value.length); //remaining textarea content
 
		textarea.focus();
	}
	else {
		var bbcode = '[' + type + '][/' + type + ']';
		textarea.value = value.substr(0, caretPos) + bbcode + value.substr(caretPos);
		textarea.focus();
		textarea.selectionStart = caretPos + 3;
		textarea.selectionEnd = caretPos + 3;
	}
}

Tags: ,

Tristan Waddington

I'm currently a senior studying public relations in the UO School of Journalism and Communication. I've been a student web developer at EMU Marketing since summer 2007.

Leave a Reply