Search code examples
javascripthtmlcsstextareacontenteditable

Prevent line breaks after certain number of lines in a text area or contenteditable div


I want to create a text area or contenteditable div (preferably a text area) that has a max number of lines where, when hitting the max line, no new line breaks are added and all new text is hidden (but still exists).

I have tried using both text areas and contenteditable div's and I have been able to get them to stop resizing after max lines but new content that is added still causes line breaks and pushes existing text out of view.

For a crude demo:

current (max lines is 3):

aaaaaaaaaaaaaaaaa (text gets hidden because of max lines)
aaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaa
aaaaaaaaa (overflows to a new line)

wanted

aaaaaaaaaaaaaaaa (text is still visible)
aaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (continues on the same line, getting hidden but still exising)

Here is a fiddle with what I have so far: fiddle


Solution

  • After a bit more research, it seems like this is not possible and it is probably better to use a custom element.

    I ended up using the maxlength attribute of a text area because I realized that I was already preventing the user from using Enter to create a new line so the number of characters in the text area was accurate enough to use.