Fixed Scroll in the DIV Jquery footer

0

Hello, I have a chat web app, it checks every x seconds of new messages, I need to go through these checks, which is via ajax, the scrool of Div #result automatically descends, p>

$('html, body').animate({scrollTop:$('#result').offset().top}, 'slow');

What's moving is the full page and up, what's wrong?

    
asked by anonymous 07.06.2017 / 23:07

1 answer

6

Would getting down would roll to the end? If yes, I think you did wrong, $('#result').offset().top takes the top position, I think for your case you would have to use height , otherwise the way you did this affected the page scroll and not the div, do so:

var container = $("#container");
var inner = $("#inner");

//Simula a entrega de mensagens
var me = true,
    msgs = [
    'Oi?',
    'Quer tc?',
    'você é de onde?',
    'Poderia me ajudar com uma duvida de JS?',
    'já usou o stack overflow?',
    'Vamos jogar um fut?'
];

setInterval(function () {
    var randomMsg = msgs[Math.floor(Math.random() * msgs.length)];
    me = me ? false : true;

    $('<p class="' + (me ? 'me' : '') + '">' + randomMsg + '</p>').appendTo(inner);
    scrollChat();
}, 1000);

function scrollChat() {
    container.stop().animate({
        "scrollTop": inner.height()
    }, 'slow');
}
#container {
    width: 240px;
    height: 280px;
    background-color: #fcfcfc;
    border: 1px #ccc solid;
    overflow: auto;
    padding: 5px;
}

#inner p {
   background-color: #4d7cfb;
   border-radius: 3px;
   color: #fff;
   margin: 5px 15px 5px 5px;
   padding: 5px;
}

#inner p.me {
   margin: 5px 5px 5px 15px;
   background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="container">
    <div id="inner"></div>
</div>
    
07.06.2017 / 23:26