According to the HTML specification, The cols attribute specifies the expected maximum number of characters per line.
This is true when the font used has the same width for every character.
According to w3schools, The cols attribute pecifies the width of the text area (in average character width).
My guess is that they mean the font's average character width and not the average character width of the text in the textarea.
Now my question is how does the user agent calculate the average character width for a certain font, what characters are included in this calculation, ... Is there a way I can get this information or calculate it myself?
What I want to do: calculate the visual number of lines inside a textarea witheout using anything else except the textContent and the cols attribute.
What I already tried:
- Calculate the average character width of the textContent:
const textSpan = document.getElementById("textSpan");
const textarea = document.getElementById("textarea");
textarea.addEventListener("input", (evt) => {
textSpan.innerText = evt.target.value;
console.log("Predicted number of lines: " + (textSpan.getBoundingClientRect().width / (textSpan.getBoundingClientRect().width / textSpan.innerText.length * 10))) // 10 = cols attribute of textarea element;
});
<textarea id="textarea" cols="10" rows="10" style="word-break: break-all;"></textarea>
<span id="textSpan"></span>
- Calculate the average character width of most characters, this may work but I have to know what characters to use for the calculation...:
const textSpan = document.getElementById("textSpan");
const textSpanACW = document.getElementById("textSpanACW");
const textarea = document.getElementById("textarea");
textarea.addEventListener("input", (evt) => {
textSpan.innerText = evt.target.value;
console.log("Predicted number of lines: " + (textSpan.getBoundingClientRect().width / (textSpanACW.getBoundingClientRect().width / textSpanACW.innerText.length * 10))) // 10 = cols attribute of textarea element;
});
<textarea id="textarea" cols="10" rows="10" style="word-break: break-all;"></textarea>
<span id="textSpanACW">abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,;?.:/=+ù%µ£^¨$*-_)àç!è§('"é&|@#¼½^{[{}</span>
<span id="textSpan"></span>
Once I have figured this out I have to get the number of visual lines without using word-break: break-all;. So that would be nice to have in the answer but not needed.