'Detecting new line while typing in a textarea [duplicate]
When i am typing in a text area, how can i detect whether the current word i am typing is the first word in the newline. I just want to find whether my current text is the new line of the text area
Is there any possibility to detect this using jquery or javascript?
Solution 1:[1]
The textarea element has an attribute named cols
. Given a text area element:
<textarea name="textarea" id="ta" rows="10" cols="50">Write something here</textarea>
you can check with an event listener (on keypress, change... whatever fits your needings) if the number of characters is larger than the number of columns:
const textArea=document.getElementById("ta");
textArea.addEventListener("keyup", () => {
const lines = ta.value.split(/\n/);
let numberOfLines = lines.length;
document.getElementById("new-lines").innerHTML = numberOfLines;
for (line of lines) {
if (line.length > ta.cols) { numberOfLines++; }
}
document.getElementById("total-lines").innerHTML = numberOfLines;
});
<textarea name="textarea" id="ta" rows="10" cols="50">Write something here</textarea>
<p>New lines (carrier return)<span id="new-lines"></span> </p>
<p>Total lines: <span id="total-lines"></span> </p>
Note: this only works with monospaced fonts
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |