Roy Genergon
Roy Genergon

Reputation: 379

Scroll to down in textarea with jQuery

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    Hello
    <p>Test</p>
  </div>
  <textarea id="one" class="inner">
    Goodbye
</textarea>
</div>

$("#one").append("your text to append");
$("#one").append("your text to append");
$("#one").append("your text to append");
$("#one").append("your text to append");

LIVE: http://jsfiddle.net/tGFmq/

how can i make automatically scroll to down in this textarea?

Upvotes: 38

Views: 39379

Answers (4)

Charles
Charles

Reputation: 1

<body>
    <textarea id="textarea-1" onfocus="setCss(this)" type="text" name="" autofocus>demo</textarea><br/>
    <button class="btn" onclick="setCss()">定位光标</button>
</body>
<script>
    function setCss(opt) {
        var sr = document.getElementById("textarea-1");
        sr.scrollTop = sr.scrollHeight;   // 内容滚动到最后一行
        var len = sr.value.length;
        setSelectionRange(sr, len, len); //将光标定位到文本最后 
        }

    function setSelectionRange(input, selectionStart, selectionEnd) {
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        }
        else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        }
    }
    </script>
</body>

Upvotes: 0

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

See this Live Demo: here

To calculate the bottom scrollTop, you can simply subtract the height from the scrollHeight:

var oneDiv = $("#one");
bottom = oneDiv.prop('scrollHeight') - oneDiv.height()

Then you can set its scrollTop to bottom, or use amazing jQuery's animate() for cool animation.

Live Demo: here

Upvotes: 11

RomoCode
RomoCode

Reputation: 1119

Add this bit to your code (preferably at the end of whatever inserts you have):

    var psconsole = $('#one');
    if(psconsole.length)
       psconsole.scrollTop(psconsole[0].scrollHeight - psconsole.height());

Upvotes: 71

Mitchell Reynolds
Mitchell Reynolds

Reputation: 41

I realised my problem was that I had the code in the incorrect place. -> Placed under the element and got the problem to solve (rookie mistake....) -- Just a reminder to all.

Upvotes: 4

Related Questions