Determine the number of lines present in a textarea

Is there a way to use JavaScript to determine the number of lines in a textarea without relying on the rows attribute? For example, in this scenario, I would expect to get 4 lines.

<textarea rows="4">Long text here foo bar lorem ipsum Long text here foo bar lorem ipsum Long text here foo bar</textarea>

Additionally, keep in mind that the textarea may have a custom style rather than the default one. Any advice on how to achieve this? Thank you!

Answer №1

This particular issue presents a challenge because attempting to call the getBoundingClientRect() method on a range within an <input> or <textarea> element will result in all browsers returning 0s for the rect values. Further details can be found here: How to get the bounding rect of selected text inside an <input>?

One workaround is to "clone" the node as a <div>, replicate the style and content of the <textarea>, and then identify the rects using the <div>. By calculating the height of all text and dividing it by the height of one character (the line-height) in the selection, you can obtain the required information.

I encountered this scenario while working on a project and found this method to be the most dependable approach for obtaining geometric data about text within <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 insert it into the DOM
clone.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 rows
range.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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Newly inserted JSON component remains invisible

I am currently using express.js to create an API. My mongoose is returning a JSON object and I need to append an element to each item in the result.docs. This is how I am attempting to achieve that: for(let a in result.docs) { result.docs[a].link ...

The bootstrap 4 modal is not displaying the button as expected

I am currently working on an Angular 4 project and I am trying to implement a pop-up using Bootstrap 4. <div> <span class="text-center" id="span1">{{title}}</span> <button type="button" class="btn primary-btn" data-toggle="modal" data ...

Ensuring Vue.js correctly re-renders an array item

In my vue.js 2 project, I am working with an array that has the following structure: data() { return { ports: [ { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}, { id: 2, ...

script loop causing an embedded form

While trying to include a Hubspot embedded form on a page using a script, I encountered an issue. I utilized onMounted to ensure the form is displayed correctly. However, upon leaving and re-entering the component where the form is located, an additional b ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Transform an array of strings into properties of an object

Looking for a way to map an array to a state object in React? Here's an example: const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"] Assuming you have the following initial state: state = { options:{} } You can achieve ...

What is the trick to displaying Bootstrap 5 dropdown arrows when the button label is lengthy?

Within a fixed-width element, I have a Bootstrap dropdown which causes the arrow to disappear when the button text is too long. Is there a way to trim the text while still displaying the arrow, similar to this image: https://i.sstatic.net/jHp5R.png .ou ...

Gather keyboard information continuously

Currently working with Angular 10 and attempting to capture window:keyup events over a specific period using RXJS. So far, I've been facing some challenges in achieving the desired outcome. Essentially, my goal is to input data and submit the request ...

Passing extra data along with dynamic routes in Reactjs

I'm currently working with Reactjs and Next.js, and I've got my [slug.js] functioning properly with the following URL: <Link href={`/${post.slug}`}><a> However, I need to pass a "hidden" additional parameter along with it. Whenever I ...

What could be causing htmlparser2 in Node.js to add extra nodes during document parsing?

Seeking to extract the HTML content of a webpage using node so I can process its DOM to create something unrelated. It's crucial to accurately obtain the DOM representation from the HTML in order to properly process it. Utilizing htmlparser2 for this ...

Remove classes from every input, textarea, and select element within a designated div using jQuery

Remove Class from Input, Textarea, and Select Elements in Specific Div Using jQuery Looking to remove a specific class from input, textarea, and select elements within a designated div using jQuery. The HTML structure is as follows: <h4 class="subHea ...

What could be causing my file input to appear misaligned?

Can anyone assist me with a strange issue I am facing? Despite using inspect element on my file input and it appearing in the correct place, it does not function as expected. To see for yourself, visit oceankarma.co and click on 'Post' at the top ...

How to assign a locally created array in a function to a globally defined array in JavaScript

Whenever I try to assign arrays, a problem arises: var arr = [ {'id': 1, 'size': 'large' }, {'id':4, 'size': 'small'} ]; function adjust(a){ var result=[{'id': 1, 'si ...

Color scheme for navigation bar carousel item background color

I have a navigation bar and carousel within the same section. I want to change the background color of both the navigation bar and carousel item when the carousel indicator becomes active. Any suggestions on how to achieve this using a jQuery function? H ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

Prevent the clustering of advertisements using jQuery

Check out my code in action here! jQuery(document).ready(function(){ var insertionTemplate = jQuery(".hiddenAdBox").eq(0).html(), insertionTarget = jQuery('ul'), insertionTargetChildren = insertionTarget.find('li'), ...

Passing variables in Node.js: passing a variable to a module versus passing a variable to each individual

As I delve into learning node.js, a question arises regarding the distinction between two different scenarios. Suppose I have a variable myvar (such as a database connection or a simple string like "test") that needs to be shared across multiple modules an ...

Retrieving an Instance of Google Maps Object with the Help of JQuery

I'm currently working on a script that, when executed, will retrieve an instance of a Google Maps object from the webpage using JQuery. For example, if there is a map present on the page, it will be structured like this: <div class="map">....& ...

What is the best way to choose a particular user from the database and display only their information?

I am looking to create a table that displays user data from my database. In essence, I have set up an auto-increment "ID" field in my users' table and now I want to include a multiple-choice box where all the users in the database are listed. These u ...

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...