Auto scroll down bar in chat div(window)

Asked

Viewed 2,056 times

1

inserir a descrição da imagem aqui

No JS manjo, but the code is 99% ready, I set some bugs, but I can’t make the scroll bar of the chat window automatically descend when inserting a new message!

How to proceed?

chat php.

<?php
        if(isset($_SESSION['logado']) && $_SESSION['logado'] === TRUE){
            try{

                $prep =  $L->prepare("Select id,nome from usuarios where id != :id ");
                $prep->bindValue(':id',$_SESSION['id']);
                $prep->execute();
                $nr = $prep->rowCount();

                if($nr > 0){
                   while($row = $prep->fetchObject()){
                       echo '<li  class="useritem"><a class="comecar" style="cursor:pointer" id="' . $row->id . '" >' . $row->nome .'</a></li>';
                   }
                }else{
                    echo '<li>Nenhum contato</li>';
                }

            } catch (PDOException $ex) {
                die($ex->getMessage());
            }

        }

            ?>

<div id='janelas'>

js scripts.

$(document).ready(function(){
    var janelas =  new Array();

    function abrir_janelas(x){
        $(".left li.useritem a ").each(function(){
           var link = $(this);
           var id = link.attr('id');
           if(id === x){
               link.click();

           }
        });
    }

    function verificar_msgs(){
        setInterval(function(){

            $.post('mensagens.php',{action:'verificar'},function(data){
               if(data !== ''){
                   for(i in data){
                        abrir_janelas(data[i]);

                   }                   
               }else{} 
            },'Json');

        },2000);
    }
    verificar_msgs();
    $("#janelas").on('click',function(){
        $.post('mensagens.php',{action:'ler_msg'},function(data){
               if(data !== ''){
                   $(".mensagens ul.lista li").addClass('lida') ;                 
               }else{} 
            },'Json');
    });
    function add_janelas(uid,nome){
        var html_add='<div class="miniwindow" id="jan_' + uid + '"><div class="usernametop" id="' + uid + '"><a href="javascript:void(0);">' + nome + '</a>&nbsp;<a href="javascript:void(0);" class="fechar" title="fechar janela">X</a></div><div class="corpo"><div class="mensagens"><ul class="listar"></ul></div></div><input type="text" class="msgbox" id="' + uid + '"  maxlength="255" /></div></div>';
        $("div.right #janelas").append(html_add);

    }
    //var miniwindow = 

    $(".useritem").on('click',function(){
        if($(this).children('a').attr('class') === 'comecar'){
            var uid = $(this).children('a').attr('id');
            var nome = $(this).children('a').html();            
            janelas.push(uid);
            for (var i = 0; i < janelas.length; i++) {
                if (janelas[i] === undefined) {         
                  janelas.splice(i, 1);
                  i--;
                }
            }
            $(this).children('a').removeClass('comecar');
            add_janelas(uid,nome);
            return false;
        }

    });

    $("body").delegate('a.fechar','click',function(){

        $(this).parent().parent().hide();
         var id = $(this).parent().attr('id');
          $(".useritem").children('a#'+id).addClass('comecar')
         $(".miniwindow #" + id).hide();
         var n = janelas.length;
         for(i=0;i<n;i++){
             if(janelas[i] !== undefined){
                 if(janelas[i] === id){
                     delete janelas[i];
                 }
             }
         }

    });

    $("body").delegate('.usernametop','click',function(){
        var pai = $(this).parent();
        var child = pai.children('.corpo');
        var isto = $(this);
        if(child.is(':hidden')){
            isto.removeClass('fixar');
            child.toggle(100);
        }else{
          isto.addClass('fixar');
            child.toggle(100);  
        }
    });

     $('body').delegate(".msgbox",'keydown',function(e){
         //alert(e.keyCode);
        var campo = $(this);
        var mensagem  =  campo.val();
        var to = $(this).attr('id');
        if(e.keyCode === 13){

            if(mensagem !== ''){
                $.post('mensagens.php',{
                    mensagem: mensagem,
                    id_para: to,
                    action:'insert'
                },function(data){
                  //console.log("--- " + data + " ---");
                    $("#jan_"+to+" .mensagens ul.listar").append(data);
                    campo.val('');
                        setTimeout(function(){
                        var textArea = document.getElementById('_');
                        textArea.scrollTop = textArea.scrollHeight;
                        }, 10);
                });
            }else{
                alert('Digite uma mensagem');
            }
        }
    });

    setInterval(function(){
        $.post('mensagens.php',{
            action:'retrieve',
            array:janelas
        },function(data){
            if(data !== ''){
                for(i in data){
                    $("#jan_"+i+" .mensagens ul.listar").html(data[i]);                    
                }
            }else{
                console.log(data + "ERRRO");
            }
        },'Json');
    },2000);
});

I guess I’ll have to add some action scrollTO() in the message insertion function, but I’m not sure.

2 answers

2

You should apply a scrollTop with the new size to each message inserted in the chat, causing the scroll to be applied.

You can use the method animate jQuery to apply a less abrupt effect to scrolling, something similar to this:

$target.animate({scrollTop: $target.height()}, 1000);

I made this simple functional example, to demonstrate the solution:

$(function() {
  $('#btn-add').click(function() {
    var message = $('#input-message').val();
    $('#messages').append("<p>" + message + "</p>");

    var $target = $('#messages');
    $target.animate({
      scrollTop: $target.height()
    }, 1000);
  });
});
#chat {
  background-color: #ddd;
}
#messages {
  background-color: #eee;
  width: 200px;
  max-height: 250px;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
  <div id="messages">
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
    <p>Teste</p>
  </div>
  <input type="text" id="input-message">
  <button id="btn-add">
    + Add Message
  </button>
</div>

Example also in jsFiddle.

0

In your anonymous message-adding function, you have to do a animate with scrollTop with the value to offset of the element in relation to the top:

$('html, body').animate({
        scrollTop: $("#jan_"+i+" .mensagens ul.listar li").last().offset().top
    }, 2000);

ps: Calhando better get a selector that goes exactly to the last li who is in the ul from the window, but since you didn’t tell us what this html is I can’t make a right selector, however - this is enough to understand the thing ;)

Browser other questions tagged

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