jQuery: Get the cursor position of text in input without browser specific code?

Ansgar picture Ansgar · Nov 3, 2010 · Viewed 128.7k times · Source

Is there any way in jQuery to get the current cursor-position in an text input without doing ugly browser specific code?

Like in:

<input id="myTextInput" type="text" value="some text" >

the cursor being after the "x" of "some text", I can get "8"?

Answer

Nick Craver picture Nick Craver · Nov 3, 2010

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.