1

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?

hindmost
  • 7,125
  • 3
  • 27
  • 39
user3791078
  • 71
  • 2
  • 5

1 Answers1

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

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59