View Full Version : [DHTML] TextFormatter

09-14-2007, 04:42 PM
1) CODE TITLE: TextFormatter

2) AUTHOR NAME/NOTES: Thomas Eding

3) DESCRIPTION: A simple class to help format strings within an element

4) URL TO CODE: http://trinithis.awardspace.com/TextFormatter/TextFormatter.js

Tested in IE6 and Fx2

Demo: http://trinithis.awardspace.com/TextFormatter/TextFormatter.html

How to use:

var tf = new TextFormatter(document.getElementById("theElement"));
tf.println(" is");
tf.println("a test!");
tf.print("x").print("y").println("f(x,y)"); //you can chain any of TextFormatter's methods like this
tf.setWidth(); //sets the width to normal if argument is <1 or absent

There are more methods than shown. Just look at the source code and look at the method names. Should be fairly obvious.

NOTE: The methods format(), formatNumber(), and newWrapper() are intended to be used indirectly through other methods.

09-14-2007, 06:35 PM
Ahh, that's pretty handy. I like it -- good work :) I would suggest some way of avoiding doing newWrapper() after every modification, though -- it really only needs to be done if text has been output since the last newWrapper().

09-14-2007, 08:11 PM
EDIT: Changed newWrapper() to check for a wrapperUsed flag, and I added a setNumberFormat(f, n) method.

setNumberFormat(f, n) only applies to print(num) or println(num) iff num is a number primitive or a Number object. Aka: print(""+num) won't work.

It accepts for f "none", "exponential", "fixed", "precision", "radix", or nothing at all, which defaults to "none". The n argument is an optional number that relates to f.

See http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Number#Methods for details. ("radix" corresponds to the toString() method.)

If anyone would like to submit any features I could add, I'll do it. (Unless of course it's something like a full-fledged version of http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax :) )