1

So, i have troubles with a textarea now, and i cant make it resize to a content width... Ive found a long and detailed answer about content height, and it works !! but not having the content width on it...

This is that post: Creating a textarea with auto-resize

BUT, my issue isnt solved, i need the width to resize too. Considering max and min widths.

This is the example code:

$("textarea").each(function () {
  this.setAttribute("style", "height:" + (this.scrollHeight) + "px;");
}).on("input", function () {
  this.style.height = 0;
  this.style.height = (this.scrollHeight) + "px";
});
$("textarea").trigger("input");
textarea{
  border: 1px solid black;
  min-width: 50px;
  max-width: 300px;
  width: auto;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.3.min.js"></script>
<textarea>this is my normal content, and it has to consider this content to be as long as the max-width</textarea>
<textarea>this is my normal content, should be consider</textarea>
<textarea>this is my min content</textarea>

Also, this is how i want them to be:

enter image description here

Excorpion
  • 235
  • 1
  • 12

1 Answers1

2

Something like this?

Note: as said in the comment, this technique uses the contenteditable property instead

#myInput {
  min-height: 20px;
  max-height: 100px;
  overflow: auto;
  border: 1px solid #000;
  border-radius: 4px;
  max-width: 80%;
  min-width: 40px;
  display: inline-block;
  padding: 7px;
  resize: vertical;
}
<div contenteditable id="myInput"></div>
savageGoat
  • 1,389
  • 1
  • 3
  • 10
  • As i said before, this resolves the issue, but not the textarea one... i need a textarea, so i can make more lines, and they stay there. – Excorpion Mar 10 '23 at 14:33
  • @excorpion you mean `[CSS] white-space: pre-line;` ? – savageGoat Mar 10 '23 at 14:54
  • Yeah, now i need to investigate how to save it with break lines, thanks – Excorpion Mar 10 '23 at 15:00
  • You either accept `\n` or translate `
    -> \n` or the other way around. It's standard practice to store the `\n` (to avoid html tags, and by extensions risks of injections) and either display it with `pre-line` or plain html by replacing them with `
    `
    – savageGoat Mar 10 '23 at 15:02
  • How can i make that replace with jquery ? – Excorpion Mar 10 '23 at 15:25
  • @excorpion first replace `
    `, something like `element.innerHTML = element.innerHTML.replace(/\
    /g, "\n")`, then get the `textContent`, I belive it's `$(elemnt).text()` in jQuery?
    – savageGoat Mar 10 '23 at 17:52
  • If you mean to display the text, `text.replace(/\n/g, "
    ")` for html, and use CSS with plain `\n`
    – savageGoat Mar 10 '23 at 17:58