How to get the number of lines in a textarea?
I have implemented the lines and lineCount methods as String prototypes:
String.prototype.lines = function() { return this.split(/\r*\n/); }
String.prototype.lineCount = function() { return this.lines().length; }
Apparently the split method will not count a carriage return and/or newline character at the end of the string (or the innerText property of a textarea) in IE9, but it will count it in Chrome 22, yielding different results.
So far I have accomodated for this by subtracting 1 from the line count when the browser is other than Internet Explorer:
String.prototype.lineCount = function() { return this.lines().length - navigator.userAgent.indexOf("MSIE") != -1); }
Hopefully someone has a better RegExp or another workaround.
Get how many lines a textarea has
This is a very difficult problem because you can't call getBoundingClientRect()
on a range within an <input>
or <textarea>
element (all browsers return 0s for the rect). See: How to get the bounding rect of selected text inside an <input>?
However, you can "clone" the node as a <div>
, copy over the <textarea>
's computed style and text, and find the rects using the <div>
. You can get the height of all of the text and divide it by the height of just one character in the selection (the line-height).
I had to do this for a project for work and this was the only reliable way to find geometry information about text inside <input>
and <textarea>
elements.
const clone = document.createElement('div');const range = document.createRange();const textarea = document.querySelector('textarea');
let rect = textarea.getBoundingClientRect();let lineHeight;let totalHeight;
// "Clone" the textarea and add it into the DOMclone.style.cssText = window.getComputedStyle(textarea).cssText;clone.style.left = rect.left + 'px';clone.style.position = 'absolute';clone.style.top = rect.top + 'px';clone.textContent = textarea.value;document.body.appendChild(clone);
// Determine the number of visible rowsrange.setStart(clone.firstChild, 0);range.setEnd(clone.firstChild, 1);rect = range.getBoundingClientRect();lineHeight = rect.height;
range.setEnd(clone.firstChild, clone.textContent.length);rect = range.getBoundingClientRect();totalHeight = rect.height;
console.log(totalHeight / lineHeight);
document.body.removeChild(clone);
<textarea rows="4">Long text here foo bar lorem ipsum Long text here foo bar lorem ipsum Long text here foo bar</textarea>
Finding number of lines in an html textarea
I haven't tried using the function discussed in this blog, but you may find it useful.
http://kirblog.idetalk.com/2010/03/calculating-cursor-position-in-textarea.html
Basically, if you create a div
and then copy the text into that div, with the same width and font characteristics, you can then get the information you need, such as the number of lines. The number of lines in this example would be easy, in that if you know how many pixels high a single line would be, then just find the width of the test div and you can get a pretty accurate idea as to how many lines are in your textarea
.
Counting textarea rows, display, increase, decrease
The code above works fine, because it is designed to return the number of rows that the textbox
displays (the attribute rows
of the textarea
). But you want the number of lines that the text inside the textarea
occupies, and here is a solution for that:
- Get the
height
of the textarea (I usedgetComputedStyle()
as the height is not defined) - Calculate the
line-height
for the content in thetextarea
(= height / rows). - Get the
scrollHeight
of thetextarea
. - Calculate the number of rows by dividing the
scrollHeight
by the calculatedline-height
.
It would be something like this:
var selector = document.querySelectorAll("textarea");
for(i = 0; i < selector.length; i++){ var txtarea = selector[i]; var count = txtarea.rows; // get the textarea height var cs = window.getComputedStyle(txtarea, null); var tHeight = parseInt(cs.getPropertyValue("height")); // calculate the line-height var tLineHeight = tHeight / count; // calculate the number of rows in the textarea var tRows = Math.round(txtarea.scrollHeight / tLineHeight); document.getElementById("results").innerHTML += "ROWS = " + tRows + "<br>"; }//end for
<textarea rows="4" cols="40"> Lorem ipsum dolor sit amet, eam ex bonorum scripserit. Audire diceret delectus ex usu. Sonet alienum duo id. Elit delenit pro ex, quo case honestatis eloquentiam ea, everti detracto intellegat no nam. Pro quodsi euismod qualisque ei. Est et modus porro, eam solet gubergren ea.
In soleat eleifend per, no per nibh mollis labitur. Sit ei possim molestiae, ius antiopam principes ei. Ea eam soleat fierent. Mel et quod veri convenire, vis no modus oporteat posidonium. Dicunt viderer vocibus his te, qui agam iriure pertinacia te. In sit homero facilisi iudicabit. Timeam eligendi sed an.
</textarea>
<textarea rows="4" cols="40"> Hello</textarea>
<div id="results"></div>
Related Topics
Detecting the System Dpi/Ppi from Js/Css
List Every Font a User'S Browser Can Display
Changing Width Property of a :Before CSS Selector Using Jquery
Find the Longest Common Starting Substring in a Set of Strings
"Thinking in Angularjs" If I Have a Jquery Background
Why Is Using the JavaScript Eval Function a Bad Idea
Is There a Dom Event That Fires When an HTML Select Element Is Closed
How to Loop Through or Enumerate a JavaScript Object
Get the Values from the "Get" Parameters (JavaScript)
Smooth Scroll Without the Use of Jquery
How to Get a Style Attribute from a CSS Class by JavaScript/Jquery
How to Build Simple Jquery Image Slider With Sliding or Opacity Effect
How to Use Jquery and Jquery Plugins With Primefaces
JavaScript Array: Get "Range" of Items
How to Randomize (Shuffle) a JavaScript Array
How to Merge Properties of Two JavaScript Objects Dynamically