'How to check if cursor is on an empty line inside textarea?
How do I check if the cursor is on an empty line inside a textarea?
I don't care about word wrapping. I care about lines that were created by hitting Enter.
$('textarea').on("change keyup", function() {
if (cursor is on an empty line or the the line has just spaces) {
console.log("empty");
} else {
console.log("has stuff");
}
});
For example:
This would log "has stuff"
The line above would log "empty" and this line would log "has stuff"
Solution 1:[1]
Another solution would be:
function is_cursor_on_empty_line(textarea)
{
// line where cursor is now
var line_number = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
// split all lines of the textarea
var lines = textarea.value.split("\n");
// current line is empty or not
return (lines[line_number-1] == '');
}
Example usage with Jquery:
var textarea = $('textarea');
if (is_cursor_on_empty_line(textarea[0]))
{
// ...
}
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 |
