4

Is it possible to get width of text inside a textarea element?

I don't want $('textarea').val().length per se, as it doesn't depend on font-size.

I would prefer the absolute width of the text inside.

1 Answer 1

9

It's well possible this information is impossible to get hold of.

Workaround idea:

  • Create a span element with the font size settings of the textarea
  • Give the span element the input's value using .text(value)
  • Measure the span's width
Sign up to request clarification or add additional context in comments.

5 Comments

@framomo86: If I can remember well, this was Facebook's approach to auto-resize the textarea accordingly to the size of the text. But instead of span I guess a pre element is better, it would jump lines with \n and wouldn't need a <br>.
Does this new span/pre need to be inserted into the page? I'm consistently getting a width of 0
@JuanCaicedo I think it might be! Give it a display: none so it doesn't show. (The dimensions should be calculated then.)
It does :) However I think visibility:hidden works better than display:none because then it still takes up space. It's good to then use absolute positioning so it doesn't move things around on the page. I followed the CSS in stackoverflow.com/questions/118241/…
Very good advise!

Your Answer

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.