This is a simple script that I use for wrapping a selected word in a textarea field. I'm looking to:

  1. make sure my logic is valid/see what others have done in a relative context.

  2. request improvements to the OO approach I'm going for.

Formatter = {};

Formatter.getSelection = function(event) {
  var text  = document.getElementById("mass_message");
  var sPos  = text.selectionStart;
  var ePos  = text.selectionEnd;
  var front = (text.value).substring(0, sPos);
  var sel   = (text.value).substring(sPos, ePos);
  var back  = (text.value).substring(ePos, text.value.length);
  format    = event.data.format;

  var print = Formatter.setString(text, format, front, back, sel);

Formatter.setString = function(text, format, front, back, sel) {
  text.value = front + "<" + format + ">" + sel + "</" + format + ">" + back;

  $( '#bolden' ).on('click', { format: "b" }, Formatter.getSelection);
  $( '#italicize' ).on('click', { format: "i" }, Formatter.getSelection);

I'm appreciative of any suggestions and am happy to answer questions about the code.


1 Answer 1


One comment I might suggest is your hard reference to mass_message, consider passing that in as part of your event data, as it makes the code more re-usable (Several instances of your editor on a page?)

A thought to consider is to swap your hard b and i tags to instead define css classes to be used? This will give you code re-use, if you had bold and italic defined in a css, you could use the above code you have to simply change the class on click instead, allowing you to do more jazzy stuff, borders and such, or be very clever and have specific things you define, maybe floats and margins/padding etc. You could use span as a first try and set the class of the span equal to the specified format :)

  • 2
    \$\begingroup\$ The bummer is i'm using textarea, which won't interpret CSS. The alternative here is to instead use an editable div, then send the div with the styles to the mailer. Provoking enough of a comment to make me think of it in a different way, thanks much. \$\endgroup\$
    – Elliott
    Oct 2, 2013 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.