Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know what lines / chars are currently visible in a textarea?

Online editor with "live preview": there is a textarea on the left and a preview div on the right. Whenever the textarea changes, the preview is updated.

This works well for small documents; for very long documents however, it becomes sluggish, because the preview has lots of DOM elements that are constantly repainted.

It would be better to only send to the preview, the part of the textarea that is currently visible (since it's the one that needs to be previewed).

There is a heuristic way to get the first visible line of the textarea:

  1. determine current scroll offset of the textarea:
    offset = scrollTop / scrollHeight
    (0 < offset < 1)
  2. the first line that is visible in the textarea is:
    (total number of lines) x offset

However this only works for "short" lines, ie lines that don't wrap. In general, the number of "lines" in a textarea is not the number of linebreaks; a long line, without linebreaks, wraps and might occupy many "line spaces".

One could try to calculate the average number of "line spaces" a line occupies (average number of characters between line breaks, width of textarea, size of font...) but this is wildly imprecise.

Is there a way to know the position of the first and last visible characters in a textarea?

like image 372
Bambax Avatar asked Sep 07 '11 09:09

Bambax


People also ask

How do I count the number of lines in a textarea?

Store the length of string in textarea as textval Then Line_no = Math. ceil(textvalue. length/n); it will give line number in which you are writting I hope it will work as you want.

Which character defines a new line in the textarea?

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

Does textarea have value?

<textarea> does not support the value attribute.


1 Answers

Well, as a crazy way for doing it you can look how ACE converts the text into canvas-drawn lines. I assume with this approach you can determine the exact position (or better to say, the exact line objects that are currently visible.

But this could also be a kind of vicious circle if the canvas-generated text is compatible in complexity to what you are having in the preview.

Alternatively you can use a fixed-width font which will give you a knowledge of the exact number of chars in the single line, and thus a way of calculating the exact first / last lines.

like image 192
Guard Avatar answered Oct 20 '22 01:10

Guard