I have a textarea and I would like to know if I am on the last line in the textarea or the first line in the textarea with my cursor with JavaScript.
I thought of grabbing the position of the first newline character and the last newline character and then grabbing the position of the cursor.
var firstNewline = $('#myTextarea').val().indexOf('\n'); var lastNewline = $('#myTextarea').val().lastIndexOf('\n'); var cursorPosition = ?????; if (cursorPosition < firstNewline) // I am on first line. else if (cursorPosition > lastNewline) // I am on last line.
jQuery solutions preferred unless JavaScript is as simple or simpler.
First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.
To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.
If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value. Keep in mind that selectionStart can only be retrieved from the following list of input types: text. password.
If there is no selection, you can use the properties .selectionStart
or .selectionEnd
(with no selection they're equal).
var cursorPosition = $('#myTextarea').prop("selectionStart");
Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.
I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With