Where is the cursor in a input or textarea?

Where is the cursor?I’ve just found a website with an interesting example forwhere is the cursor and which text is selected (if any) in an input and textarea.

The truth is this code is not for daily use, but it’s quite interesting to see the possibilities of javascript (well in fact I was looking for this because I need it, but it’s not the usual).

In the example on that page, the functions getSelectionStart and getSelectionEnd are used. The first one, as one might realize, says where is the cursor on the input or textarea, while the other tells where ends the selection (and a selection exists when getSelectionStart() != getSelectionEnd()).

Following the javascript functions I was talking about:

function getSelectionStart(o) {
 if (o.createTextRange) {
   var r = document.selection.createRange().duplicate();
   r.moveEnd('character', o.value.length);
   if (r.text == '') return o.value.length;
   return o.value.lastIndexOf(r.text);
 }
 else {
    return o.selectionStart;
 }
}
 
function getSelectionEnd(o) {
 if (o.createTextRange) {
 var r = document.selection.createRange().duplicate();
 r.moveStart('character', -o.value.length);
 return r.text.length;
 } else {
   return o.selectionEnd;
 }
}

Trackback URL

, , , , ,

Comments are closed.