1

After a lot of research, I haven't found a post with exactly the same requirements so I thought write a new post.

I'm trying to create a fixed area (e.g. 200px by 300px) where the user can enter text input. He should be able to enter any character (including line breaks).

However, he should not be able to 'write outside the box' (i.e. there shouldn't be overflow scroll or hidden for the 200x300 area).

Once user reaches the 'bottom' of the area, they can't enter any more line breaks.

And once they reach the 'bottom right' corner of the 200x300 area, they shouldn't be able to enter any more characters at all.

Is this possible in css, angular, js, jquery, etc?

cj780
  • 11
  • 4

3 Answers3

0

Limit the length of characters with base in font and div's size, but you must change the font size and family or line height because every browser can have different styles.

To limit the length of characters in the div is need to ignore the HTML tags in the content, like interpreting.

Firstly calculate how many characters fits there.

0

You can restrict the number of characters per line with the cols="" attribute and set the displayed the number of editable lines with the rows="" attribute. However limiting the number of rows could only be one with the maxlength attribute which would control the number of characters you can have, which you'd have to estimate. There are some hacks to limit the number of rows with event listeners, but they seem to have fairly major bugs.

Community
  • 1
  • 1
Anders Elmgren
  • 637
  • 5
  • 12
0

It is possible, you just need to do following:

  • Use event handlers to control character input process. It is required to be able to stop processing further keystrokes when limit is reached. Use keypress and keydown, first handles character processing, second - control keys processing.
  • Each time user presses a key, use a separate buffer to produce final result, compute its bounding rectangle, and if it is bigger than limit, prevent event handling.
  • Height of text body could be calculated by multiplying number of lines by line height (interpret font-size and line-height CSS properties).
  • Width of text body could be computed rather easy with help of HTML5 canvas measureText method.
  • If you don't have canvas, you can use offscreen span (or any other inline) element - just fill innerHTML with text block and use its offsetWidth attribute. Actually, if you replace line break characters with <br>, you may use span approach to get both dimensions in one go - just make sure it has same style as editable container.

ContentEditable containers, as i remember, store text body in HTML format already (in other words - with <br>s instead of line break characters).

weaknespase
  • 1,014
  • 8
  • 15