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.

Jesse W. Collins
  • 139
  • 1
  • 1
  • 12
framomo86
  • 1,205
  • 2
  • 14
  • 17

1 Answers1

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
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 1
    Nice workaround! I wait for some other ansers before accept it – framomo86 Oct 17 '10 at 13:02
  • 7
    @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 `
    `.
    – BrunoLM Oct 17 '10 at 15:20
  • Does this new span/pre need to be inserted into the page? I'm consistently getting a width of 0 – JuanCaicedo Jun 07 '17 at 11:52
  • @JuanCaicedo I think it might be! Give it a `display: none` so it doesn't show. (The dimensions *should* be calculated then.) – Pekka Jun 07 '17 at 12:21
  • 1
    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 https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – JuanCaicedo Jun 07 '17 at 12:24
  • Very good advise! – 이승현 Dec 30 '22 at 12:45