Click here to Skip to main content
15,884,425 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This textarea is resizable and has a close button to enter text and close the textarea. Only text remains, but there is no
at this time.
The result is shown below.
Is there a way to insert a line break to fit the size of the textarea?


[------------------[O X]
| text text text text tex|
|t text text text text te|
|t______________________|

after click "O". No line break.
text text text text text text text text text text"


I want this.
text text text text tex\r\b
ext text text text tex\r\b
t

What I have tried:

JavaScript
document.getElemenyById('closebtn').addEventListener('click'), (e) =>{
    addlinebr(e)
}

addlinebr(_e) = function(){
   var texta = $("#texta");
   var text = texta.val();  // text
   var tsize = texta.attr("font-size");  // font size
   var a_width = texta.width();   // textarea width
   /* I don't know how... */
}
Posted
Updated 30-Dec-22 8:32am

It sounds like you're trying to do something that you shouldn't be doing. There is no reliable way to do that because as the text area size changes, you're going to have to go through the text, remove any existing line breaks, and put new ones in for the new size. That's just stupid.

You might want to start by explaining what it is you're really doing with the text area and why you want line breaks inside word boundaries.
 
Share this answer
 
Comments
Chopin2001 30-Dec-22 14:33pm    
Below is the improved code.
Dave Kreskowiak 30-Dec-22 14:50pm    
You posted your code snippet as an answer to your own question.

Ignoring that, your code, as posted, is silently failing because of a misspelling.

And you never said why you want to do this. I can't think of a single valid reason to do it.
This work.

JavaScript
var selection;
if(window.getSelection){
   selection = window.getSelection();
}

var input = document.getElementById("textarea");
const input_width = input.width();
const hidden = $("hidden");
const hidden_width = hidden.width();
var select;
var text = input.val();

for(n = 0; text.length; n++){
   input.prop('selectionEnd', n);
   select = selection.toString();
   hidden.html(select);
   if( hidde.width > input_width ){
      insertAtCaret("\r\n");
   }
}

insertAtCaret = function(input, text){
   input.setRangeText(
      text, // text insert to
      input.selectionEnd, // point to start change
      input.selectionEnd, // point to end change
      'end') // after position of caret.
}

But this is slow.
Are there any better improvements?
Thanks!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900