calculate string width dynamically

S

strauchdieb

hey everyone

i try to figure out how to calculate string width in a textarea while
typing in it.
the textarea has a fixed start width. when the string gets longer as
the textarea width, the textarea should be made bigger while typing
programatically.

my only problem is to determine the size of the string in the textarea.
i know the font family and font size.

who can help me?

thanks for your help
 
T

Touffy

i try to figure out how to calculate string width in a textarea while
typing in it.

you mean a text input, or really a multiline textarea ?
the textarea has a fixed start width. when the string gets longer as
the textarea width, the textarea should be made bigger while typing
programatically.

my only problem is to determine the size of the string in the textarea.
i know the font family and font size.

If you use a monospace font, then the text should take exactly as many
ems as there are characters on the longest line (use split(/\n\r?/) on
the value, and find the longest string in the returned array), so you
can set the textareas's style.width to that length+"em".

You may want to replace() tabs in the value with a predetermined number
of spaces before counting the characters.

If you're not using a monospace font, you can still measure the length
of the value but not inside a form input. You'll have to copy the value
inside an invisible/offscreen (but with a display:block) div with
white-space:pre and the same font-family and font-size as the textarea.
Once this div is created and rendered (a short setTimeout might be in
order), you can read its offsetWidth or clientWidth property (try both
because some browsers support only one) and that's the width in pixels,
that you can apply to the textarea after adding the unit "px".
Doing all this would probably take more time than you care to spend on
every keydown event, though...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,525
Members
44,997
Latest member
mileyka

Latest Threads

Top