I have a textarea that is hooked up to line numbers that are made with an ordered list, but I want to be able to tell when a new line is created and when a line is deleted such as to add or delete ordered list elements such that the amount of ordered list elements corresponds with the number of lines in the textarea.
I have figured that whenever a new line is created, the enter key is being used to do so, and that when a line is deleted, that sometimes happens when backspace is used.
I have event listeners for the textarea, with the id of "objtext", as so:
//get the objtext element
var objtext=document.getElementById("objtext");
//detect keypress
objtext.addEventListener("keydown",(e)=>{
//detect new line
if(e.key="Enter"){
//add an ordered list element
}
if(e.key="Backspace"){
//check what key was deleted
//how can this be done?
if("\n" was removed){
//remove an ordered list element
}
//and what about when a new line was removed?
if(some text was removed such that it removes a line){
//remove an ordered list element
}
}else if(some text was added such that it adds a line){
//add an ordered list element
}
});
But even if I could figure that out, the using enter to get a new line only works for new paragraphs, as in what about the times the text overflows the textarea onto a new line? And what about when backspace is used to delete some words such that it goes back up a line?
How could this be done?
Like I said in the comments perhaps counting line breaks on each key stroke is easiest.
Note that when a line wraps due to insufficient space inside the textarea, we won't count the wrap as line break.
const objtext = document.getElementById("objtext");
objtext.addEventListener("keyup", (event) => {
const output = document.getElementById("output");
const lines = event.target.value.split('\n').length;
// now do with lines what you like
output.textContent = `The textarea has ${lines} line breaks`;
});
#output {
display: block;
margin-top: 1rem;
}
<textarea id="objtext"></textarea>
<span id="output">The textarea has 0 line breaks</span>