views:

43

answers:

1

I have some code to insert tags to textarea (for Internet Explorer). But I have problem with IE8. If there is lots of text and I try to insert text somewhere in the end - it's scrolled up.

Code:

<script type="text/javascript">
function bold()
{
    var text1 = document.getElementById('text1');
    var sel = '';
    if (document.selection) 
    {
        sel = document.selection.createRange();
        sel = sel.text;
    }
    if(sel)
    {
        text1.focus();
        document.selection.createRange().text = '<strong>' + sel + '</strong>';
    }
}
</script>

<textarea id="text1" rows="10" style="width:100%;"></textarea>
<br />
<input type="button" value="bold" onclick="bold();" />

It's happens only if I set width to textarea, so code works ok with this markup:

<textarea id="text1" rows="10" cols="80"></textarea>
+2  A: 

Two options:

  • Manipulate the scrollTop property to move the scrollbar to the end:
text1.scrollTop = text1.scrollHeight;
  • Move the caret to the desired position using the moveStart() method.
Andy E
Thanks a lot. It helps me so i found that it's enough to add textRange.select() method after insert.
x2
`textRange.select()` is definitely the way to go. You can then collapse it if needs be.
Tim Down