javascript - How to get the caret position in a textarea, in characters, from the start? -


how caret position in <textarea> using javascript?

for example: this is| text

this should return 7.

how return strings surrounding cursor / selection?

e.g.: 'this is', '', ' text'.

if word “is” highlighted, return 'this ', 'is', ' text'.

with firefox, safari (and other gecko based browsers) can use textarea.selectionstart, ie doesn't work, have this:

function getcaret(node) {   if (node.selectionstart) {     return node.selectionstart;   } else if (!document.selection) {     return 0;   }    var c = "\001",       sel = document.selection.createrange(),       dul = sel.duplicate(),       len = 0;    dul.movetoelementtext(node);   sel.text = c;   len = dul.text.indexof(c);   sel.movestart('character',-1);   sel.text = "";   return len; } 

(complete code here)

i recommend check jquery fieldselection plugin, allows , more...

edit: re-implemented above code:

function getcaret(el) {    if (el.selectionstart) {      return el.selectionstart;    } else if (document.selection) {      el.focus();       var r = document.selection.createrange();      if (r == null) {        return 0;      }       var re = el.createtextrange(),          rc = re.duplicate();      re.movetobookmark(r.getbookmark());      rc.setendpoint('endtostart', re);       return rc.text.length;    }     return 0;  } 

check example here.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -