HELP I have a problem with the scroll of my chatroom

2

I have a problem with the scroll of my chatroom The scrollHeight all the time stays down and does not move to see the messages above

  • what I want to do is move the scroll of the user so that I can see all the chat messages and stay where the user wants if someone can help me I appreciate it

-If you need all the file tell me ...

//tiempo real del chat 1000 es un segundo 
setInterval("mostrar_enviado()",500);
mostrar_enviado();

//aqui nos deja ver el chat

    function mostrar_enviado(){

        var parametros = {
            "pconsulta" : "mostrar_mensajes",
        }       

        $.ajax({
            data: parametros,
            url: 'valida_ajax.php?v=<?php echo $id; ?>',
            type: 'POST',
            befforesed: function(){
            },
            success: function (response){
                document.getElementById("mostrar_mensaje").innerHTML=response;
                var abajo=$("#mostrar_mensaje").prop("scrollHeight");
                $("#mostrar_mensaje").scrollTop(abajo)              
            }
        });     

    }
    
asked by Shareiv 09.02.2017 в 00:56
source

1 answer

0

If I have understood the description well, the problem is that you can not upload in the chat and see the previous messages. That may be due to how the JavaScript works:

  • The mostrar_enviado() function is called every 500 milliseconds (2 times per second)
  • In the mostrar_enviado() function an AJAX call is made and when the response of the request is received:
  • The returned text is written
  • The height of the text container is calculated
  • Scroll to the bottom of the container

As soon as there is going to be a problem (which can be seen in the code above): 2 times every second is scrolled to the bottom of the chat, which will make you try to upload, but do not do that action because it is programmatically downloaded.

One solution to prevent this from happening would be to return something more than the chat text, for example JSON with the chat text and a timestamp with the date and time of the last message. Then only scroll to abajo if there is new content (which would allow scrolling up because the JS would not undo the scroll that the user does).

For example, if what was returned in the AJAX call was something like this:

{
  "ultimoMensaje": 1486605917,
  "conversacion": "...."
}

Then in the success you would have to add a condition:

....
success: function (response){
    if (response.ultimoMensaje > ultimoMensajeMostrado) {
        ultimoMensajeMostrado = response.ultimoMensaje;
        document.getElementById("mostrar_mensaje").innerHTML = response.conversacion;
        var abajo=$("#mostrar_mensaje").prop("scrollHeight");
        $("#mostrar_mensaje").scrollTop(abajo);
    }
}
....
    
answered by 09.02.2017 / 03:03
source