Fixed Scroll in DIV Jquery footer

Asked

Viewed 163 times

0

Opa, I have a web chat application, it does checks every x seconds of new messages, need that at the end of these checks, which is via ajax, the scrool of Div #result automatically descend, I tried so:

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

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

1 answer

5


Would going down be to roll to the end? If yes I believe you did wrong, the $('#result').offset().top takes the position of the "top", I believe that for your case you would have to use the height, out of the way you did this affecting the page scroll and not div scroll, 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>

<div id="container">
    <div id="inner"></div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.