example html: javascript: var theTextBox = $('#textbox')[0]; //make a reference for accessing it multiple times var bbCode = { bbCode_Bold : { encloseLeft : "[b]", encloseRight : "[/b]"}, bbCode_Italic : { encloseLeft : "[i]", encloseRight : "[/i]"}, }; $('.bbButtons').mouseup(function(){ //add event handler to each button var buttonID = $(this).attr('id'); //assign the id of the button that was clicked to a variable var currentValue = theTextBox.value; //assign the text that is currently in the textbox to a variable theSelection = document.selection.createRange().text; //assign the text that is currently selected in the textbox to a variable if(theSelection === ""){ //if they haven't selected anything if (((currentValue.split(bbCode[buttonID].encloseLeft).length+currentValue.split(bbCode[buttonID].encloseRight).length) % 2) == 0){ //if the the number of "encloseLeft" bbcode's & the number of "encloseRight" bbcode's in the text box is even theTextBox.focus(); //make sure the cursor is in the text box document.selection.createRange().text = bbCode[buttonID].encloseLeft; //add a left bbcode (e.g. [b]) return; } else{ theTextBox.focus(); //make sure the cursor is in the text box document.selection.createRange().text = bbCode[buttonID].encloseRight; //add a right bbcode (e.g. [/b]) return; } } else{ //if they have selected text document.selection.createRange().text = bbCode[buttonID].encloseLeft + theSelection + bbCode[buttonID].encloseRight; //wrap the selection in the bbcode buttons and assign it to the "document.selection.createRange().text" which will paste it into the textbox return; } theTextBox.focus(); //make sure the cursor is in the text box theSelection = ""; //empty theSelection variable });