Scroll down automatic scroll bar in chat div (window)

1

NoJShandle,however,thecodeis99%ready,Ifixedsomebugs,butIcannotmakethechatwindowscrolldownautomaticallywhenIinsertanewmessage!

Howtoproceed?

chat.php

<?phpif(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'>

scripts.js

$(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 think I have to add some action of scrollTO() to the insert message function, but I'm not sure.

    
asked by anonymous 04.04.2016 / 14:30

2 answers

1

You should apply a scrollTop to the new size for each message you enter in the chat, making the scroll applied.

You can use jQuery's animate method to apply a less abrupt effect to scrolling, something like 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><divid="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.

    
04.04.2016 / 14:59
0

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

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

ps: It's better to get a selector that goes exactly to the last li that is in ul of the window, but since you did not tell me what the html is, I can not make a However - this comes to realize the thing;)

    
04.04.2016 / 14:41