Donde está el cursor?

Where is the cursor?Buscando y buscando, me acabo de encontrar con una web que tiene un ejemplo muy interesante y que nos dice dónde está el cursor en un input o textarea en cada momento, y además permite saber cual es el texto seleccionado (si es que lo hay).

La verdad es que no es algo que a uno le haga falta todos los días, pero a mi me hacía falta y me ha resuelto el problema.

En el ejemplo que hay en dicha página se usan las funciones getSelectionStart y getSelectionEnd. La primera nos dice donde está el cursor, mientras que la segunda nos dice dónde finaliza la selección (siempre y cuando getSelectionEnd devuelva un valor distinto a getSelectionStart).

A continuación teneis estas dos funciones:

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

, , , , ,

16 Comments on "Donde está el cursor?"

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Subscribe to Comments