Forum Moderators: open

Message Too Old, No Replies

Textarea focus cursor position?

         

appi2

7:29 pm on Aug 1, 2007 (gmt 0)

10+ Year Member



Say I have a textarea.
<textarea id="foo"></textarea>

I can get the focus/cursor at the end of the textarea value by

document.getElementById("foo").value = "Happy kittens dancing"
document.getElementById("foo").focus()

Is there a way to get the focus/cursor after the word kittens?

Or even is there a way to find the focus/cursor position if the user clicks anywhere between the string?

birdbrain

9:12 am on Aug 2, 2007 (gmt 0)



Hi there appi2,

have a look at this example, it may suit your requirements...


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>set cursor position</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
window.onload=function() {
setCursor(document.getElementById('input1'),13,13)
}
function setCursor(el,st,end) {
if(el.setSelectionRange) {
el.focus();
el.setSelectionRange(st,end);
}
else {
if(el.createTextRange) {
range=el.createTextRange();
range.collapse(true);
range.moveEnd('character',end);
range.moveStart('character',st);
range.select();
}
}
}
</script>

</head>
<body>

<div>
<textarea id="input1" name="input1" rows="10" cols="30">Happy kittens dancing</textarea>
</div>

</body>
</html>

birdbrain

appi2

8:54 am on Aug 3, 2007 (gmt 0)

10+ Year Member



Thanks thats what I needed.

setSelectionRange mozilla
createTextRange IE

birdbrain

10:10 am on Aug 3, 2007 (gmt 0)



No problem, you're welcome. ;)