6
\$\begingroup\$

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;
}
$(document).ready(function(){
 $( '#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.

Malachi
29k11 gold badges86 silver badges188 bronze badges
asked Oct 2, 2013 at 15:26
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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 :)

answered Oct 2, 2013 at 16:37
\$\endgroup\$
1
  • 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\$ Commented Oct 2, 2013 at 17:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.