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)

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

Declare a jQuery variable containing HTML elements

Greetings! I am facing an issue while attempting to create a jQuery variable that stores a table meant for displaying in different sections of a website. Unfortunately, I am encountering an error and struggling to comprehend the reason behind it. Below is ...

Avoiding the triggering of jQuery events from child elements

Here is the code snippet I am working with: <html> <head> <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"> </script> </head> <body> <div id=&q ...

The submit function in JQuery may not work as expected when attempting to submit a form in Internet

I'm dealing with a form that submits values to JQuery code, triggering an email with the form data. The issue is that it works flawlessly on Firefox but fails on IE6 and IE7. Any idea why this might be happening? Your insights would be greatly appreci ...

Utilizing mapped data to display numerous Material-UI Dialog elements

On my table, I have a list of users displayed. Each user has a button in their row to delete them. Clicking the delete button triggers a Material-UI Dialog to confirm. An issue arises where 3 dialogs are being rendered due to mapping, and the last dialog ...

Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material alw ...

What are the problems with Internet Explorer in Selenium WebDriver?

Currently dealing with a mouse-over issue in IE while using webdriver code. The functionality works smoothly in Chrome and Firefox, however, the problem arises only in IE. How can I resolve this? Initially focusing on an element and then clicking on a li ...

The issue with Postman Express.js Response Body not displaying any content is quite common

I've been struggling with this issue for a whole day and I just can't seem to find a solution. My node app is extremely simple. const express = require("express"); const port = 3001; const app = express(); app.use(express.json()); app.pos ...

Interact with database using Ajax and Codeigniter (utilizing Bootstrap modal)

My goal is to create an advanced search feature with an interactive button that opens input fields and dropdown menus. To populate these dropdown menus with data from the database without overloading the page, I plan to use AJAX when the user triggers the ...

Concerning dilemma with a div element

I am using 2 different partial views in my main view: <div class="col-md-6"> @Html.Action("Chart", "Teams") </div> <div class="col-md-6"> @Html.Action("SeriesWinsChart", "Teams") </div> <div class="next-game"> & ...

Issue with React when attempting to add a secondary class to Toggle component

Is there a way to add a second class to my <div> with the class "button"? When I try to append 'toggle-button', the class doesn't seem to work. <CSSTransitionGroup transitionName="buttonAninmated" transitionEnterTimeout={30 ...

modifying anchor tag's href attribute using jQuery

I require assistance in changing the href tag using jQuery, here is my current code: $(document).ready(function () { var hScreen = $(window).height(); var lScreen = $(window).width(); if(hScreen < 800){ } }); Now I want to implement ...

Utilizing the Grid-A-Licious plugin multiple times within a single webpage

Currently, I am utilizing the Grid-A-Licious plugin for my project. It functions perfectly when used on a single page with one call to the plugin. However, due to my design requirements, I need to implement it within 3 tabs on the same page. Unfortunately, ...

Using The Telerik AJAX radComboBox to Retrieve the SelectedValue from a Secondary comboBox

Iā€™m attempting to fill a Telerik AJAX radComboBox with the results from another. For example: comboBox1 ā€“ auto-completes and user makes a selection comboBox2 ā€“ user selects. Loads on demand. It uses the selected value from comboBox1 to populate its ...

How can I customize the <span> element created by material-ui?

Is there a way I can customize the appearance of the <span> tag that is produced when using the Checkbox component from the material-ui library? Essentially, I am seeking a method to alter: <span class="MuiButtonBase-root-29 MuiIconButton-root-2 ...

What is the process for incorporating a custom script into a pre-existing node.js library?

I am facing a challenge with integrating a personal script with custom functions into my local copy of the hls.js library. How can I successfully add a new script to the library and then utilize the functions written within it? To provide context, let&apos ...

Retrieve user-specific relational data

In my Supabase database, I have three main tables: users, teams, and members. The users table stores information about all users who sign up using auth. Here are the details contained in this table: id displayname email 602eff1e-6300-491e-b821-44e ...

Click the button to trigger the pop-up

After creating a photo gallery using a plugin, my goal is to display this gallery when the user clicks on my homepage button. I am unsure how to make this happen and would appreciate any assistance. Below is my button code: <div class="ow-button-base ...

Issue with ExpressJS Twig module: inability to execute async functions even after adjusting settings as needed

Currently, I am facing an issue while trying to load an array from mongoose into a twig rendered list. An error message keeps popping up: TwigException: You are using Twig.js in sync mode in combination with async extensions. I have made sure to care ...

Collaboratively utilizing resources among various NPM Workspaces

Currently, I am working on a React project using NPM Workspaces. I have created an 'assets' workspace within this project to store all images and assets that need to be accessed by other workspaces. The directory structure of the project is as fo ...

Swapping out nodes for images using d3.js

Below is the code snippet I am currently executing http://jsfiddle.net/a7as6/14/ I have implemented the following code to convert a node to an image: node.append("svg:image") .attr("class", "circle") .attr("xlink:href", "https://github.com/favico ...