What is the best way to restrict the length and number of lines in a textarea based on pixel dimensions?

I am looking to create a textarea where people can select different fonts, such as "sans-serif" and "serif", to type in text. I plan to have buttons labeled "sans-serif" and "serif" that will change the font of the textarea when clicked.

However, there are some conditions:

  1. The total line limit of the textarea cannot exceed 4 lines.

  2. Each line cannot be more than 100px wide in terms of characters inputted by the user.

  3. If a line exceeds 100px, it should automatically move to the next line.

  4. Once the user reaches line 5, they should no longer be able to input text.

I believe using HTML5 canvas with JavaScript/jQuery would be ideal. However, I need a function to change the font of the textarea. Do you have any suggestions for this?

Here is the HTML and CSS setup:

HTML:

<textarea id="testarea"></textarea>
<br>
<div class="btn" onclick="$('#testarea').css('font-family', 'sans-serif');">Sans-serif</div>
<div class="btn" onclick="$('#testarea').css('font-family', 'serif');">Serif</div>

CSS:

#testarea{
  resize: none;
  width: 300px;
  height: 232px;
  font-size: 16px;
  line-height: 1.45;
}
.btn{
  cursor: pointer;
  display: inline-block;
  background: green;
  padding: 10px;
}

Answer №1

After much consideration, I have devised a potential solution with some assumptions in place. Please read the full answer for details.

  1. The textarea's maximum total line limit is set to 4 - Included
  2. Each line cannot exceed 100px in length (considering user input characters) - Included
  3. If a line surpasses 100px worth of characters, it will automatically move to the next line - Included
  4. User typing is restricted after reaching the 5th line - Included

New additions:

  1. No more than 4 lines allowed in JS (Max 4)
  2. Given that the font-size in the textarea is set to 16px, resulting in 100/16 = 6.25. The maximum characters per line has been capped at 6
  3. If there are more than 6 characters in one line, the excess will be moved to the next line
  4. User cannot exceed typing beyond 4 lines

Answer:

var textarea = document.getElementById("testarea");
textarea.onkeyup = function() {
  var lines = textarea.value.split("\n");
  for (var i = 0; i < lines.length; i++) {
    if (lines[i].length <= 6) continue;
    var j = 0;
    space = 6;
    while (j++ <= 6) {
      if (lines[i].charAt(j) === " ") space = j;
    }
    lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
    lines[i] = lines[i].substring(0, space);
  }
  textarea.value = lines.slice(0, 4).join("\n");
};
#testarea {
  resize: none;
  width: 300px;
  height: 232px;
  font-size: 16px;
  line-height: 1.45;
}

.btn {
  cursor: pointer;
  display: inline-block;
  background: green;
  padding: 10px;
}
<textarea id="testarea"></textarea>
<br>
<div>
  <button class="btn" type="button" onclick="myFunction()">Comic Sans</button>
</div>

<div>
  <button class="btn" type="button" onclick="myFunction_2()">Reset</button>
</div>

<script>
  function myFunction() {
    document.getElementById("testarea").style.font = "italic bold 25px Comic Sans MS, Comic Sans MS, Comic Sans, cursive";
  }
</script>

<script>
  function myFunction_2() {
    document.getElementById("testarea").style.font = "italic normal 16px Arial, Helvetica, sans-serif";
  }
</script>

Output Sample

(Input text and press Enter to move to the next line) https://i.sstatic.net/wsy4F.png

Conclusion:

Adjust as needed based on your requirements.

Note:

  1. Code quality may need improvement, make changes accordingly.
  2. Assumption is made that the textarea will maintain a fixed font-size
  3. Changes in font triggered by button clicks might not align with the specified requirements.

Wishing you a wonderful day.

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

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

Toggle the active class on the parent element when it is clicked

I'm encountering a problem with my JavaScript - attempting to make this function properly. Firstly, here is the desired functionality: 1.) Add or remove the 'active' class from the parent element when clicked 2.) When clicking inside the ...

Packages have gone astray post node_modules scrub

I encountered an issue with npm run watch getting stuck at 10%, so I took the step of deleting the node_modules directory and package-lock.json. However, it seems that I may have installed modules using npm install without the --save-dev option. Even after ...

Update the second dropdown menu dynamically according to the choice made in the first dropdown list

I need help with creating two drop down lists, ddl1 and ddl2. When an item is selected in ddl1, I want the corresponding items to be populated in ddl2. For example, if "Accounts" is selected in ddl1, then ddl2 should display "Account officer, Account man ...

Error message: jQuery expression not being detected

Here is some html code that I have in my view: <div id="divLoginName" style="display: none"> <input type="hidden" id="hidLoginName" /> @Html.TextBox("txtEditLoginName", null, new { maxlength = "1000", tabindex = "0", Multiline ...

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

Tips for accessing a jQuery tab UI that is on a separate page by utilizing AJAX techniques

My project is a web application built in Eclipse using JSP, AJAX, and jQuery. It consists of two main JSP pages - home.jsp and second.jsp. Additionally, there are separate folders for css and js files. In second.jsp, I have implemented tab panels using di ...

Checking URL validity using JavaScript Regex

I attempted to validate a URL with or without the http protocol, but no matter what I tried, the function kept returning false. I verified my regex string on this website: And it appeared as expected. function isUrlValid(userInput) { var rege ...

What could be causing my completed torrents to sometimes not be saved to my disk?

Currently, I am working on developing a small torrent client using electron and webtorrent. Although everything appears to be functioning correctly initially, there is an issue where sometimes the resulting files from a finished download are not being save ...

What could be causing the extra space at the top of my div element?

My goal is to accomplish the following: However, there appears to be an unnecessary gap above the Social icons div. You can view the live page at This is my current markup:- <header> <img src="images/home-layout_02.jpg" alt="Salem Al Hajri Logo ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

Encountering an issue where attempting to map through a property generated by the getStaticProps function results in a "cannot read properties

Greetings, I am fairly new to the world of Next.js and React, so kindly bear with me as I share my query. I have written some code within the getStaticProps function in Next.js to fetch data from an API and return it. The data seems to be processed correct ...

Experiencing difficulty inputting data into database using PDO

Attempting to save user input data to a database using PDO, I have created a form for users to input their information. However, when I submit the form, it redirects to proses_input.php and displays a blank page. I tried combining the code into one file, b ...

Numerous hyperlinks leading to different products within the same image

https://i.sstatic.net/T7P4V.jpg I am looking for a solution to create clickable links on a picture that contains multiple items (3 in my specific case, as shown in the image above). Currently, I am using position:absolute to place links on each item, but ...

Vue-moment displaying incorrect time despite timezone setting

Feeling a bit puzzled about my Laravel 8 application. I store time in UTC with timestamp_no_timezone in my PostgreSQL database. When I check the time in the database, it displays today's date with 13:45 as the time. However, when I use vue-moment and ...

What is the process for registering a click using a class in jQuery and retrieving the ID of the clicked element?

Currently, I am working on developing a webpage where I need to use jQuery to register a click using the items class and then extract the ID of that particular object. For example: HTML: <div class="exampleclass" id="exampleid1"></div> <d ...

What might be causing my Vue unit test to overlook a function?

I am in the process of creating unit tests for my component dateFormat.js using Jest. The focus is on testing the function formatDateGlobal. Here is an excerpt from the test: import DateFormat from '../dateFormat'; describe('dateFormat.js& ...