Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - If cursor position at the start/end in a textfield

i have a textarea and I want to check if the cursor is at the start or at the end (I dont need the current position).
Did anybody know a simple jQuery solution?

Thanks in advance!
Peter

like image 737
Peter Avatar asked Oct 11 '10 08:10

Peter


People also ask

How to set cursor position in textBox in HTML?

value + "\n"; ele. focus(); // To update cursor position to recently added character in textBox ele. setSelectionRange(value. length, value.

How do I find my cursor position?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

How do I get the input field cursor?

Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.


1 Answers

Assuming you mean a <input type="text"> rather than a textarea, here's a non-jQuery solution (that you can still use with your jQuery code). It will almost certainly be less code than a jQuery plug-in.

UPDATE 12 November 2011

Having said that, I have developed a jQuery plug-in for just his kind of task, and it is indeed bigger than the code below.

var textInput = document.getElementById("your_id"), val = textInput.value;
var isAtStart = false, isAtEnd = false;
if (typeof textInput.selectionStart == "number") {
    // Non-IE browsers
    isAtStart = (textInput.selectionStart == 0);
    isAtEnd = (textInput.selectionEnd == val.length);
} else if (document.selection && document.selection.createRange) {
    // IE <= 8 branch
    textInput.focus();
    var selRange = document.selection.createRange();
    var inputRange = textInput.createTextRange();
    var inputSelRange = inputRange.duplicate();
    inputSelRange.moveToBookmark(selRange.getBookmark());
    isAtStart = inputSelRange.compareEndPoints("StartToStart", inputRange) == 0;
    isAtEnd = inputSelRange.compareEndPoints("EndToEnd", inputRange) == 0;
}

alert("At start: " + isAtStart + ", at end: " + isAtEnd);
like image 134
Tim Down Avatar answered Oct 16 '22 00:10

Tim Down