1

I am making a web chat application in which I have added some cool features like clear chat buttons and all...
But I am facing this problem..
Whenever I append more messages which exceed the div height, it shows the scroll bar but does not scroll down to show the client a new message. Can somebody help me fix that please.

Here is its index.html code:(I can not send the server.js code since it runs by node.js)

    var socketio = io();
     function update(list)
     {
        for(var i = 0; i < list.length; i++)
        {
            $("#users").append("" + list[i] + ", ");
        }
     }
    // block
    $("#login-form").submit(function(event){
        event.preventDefault();
        if($("#username").val() == "" || $("#username").val() == " ")
        {
            alert("Please enter a valid username.");
        }
        else
        {
            $username = $("#username").val();

            $("#total").hide();
            $("#chat-area").show();
            $("#messages").html("");
            socketio.emit("has connected", $username);
        }
    });
    $("#message-form").submit(function(event){
        event.preventDefault();
        if($("#message").val() == "" || $("#message").val() == " ")
        {
            alert("Please enter a message.");
        }
        else
        {
            socketio.emit("new message", {username: $username, message: $("#message").val()});
            $("#message").val("");
        }
    });
        socketio.on("has connected", function(data) {
            $("#users").html("");
            update(data.usersList);
            $("#messages").append("<li><i><b>"+ data.username +"</b> has connected</i></li>");
        });
        socketio.on("has disconnected", function(data) {
            $("#users").html("");
            update(data.usersList);
            $("#messages").append("<li><i><b>"+ data.username +"</b> has disconnected</i></li>");
        });
        socketio.on("new message", function(data) {
            if(data.username == $username)
            {
            $("#messages").append("<li><b>You</b>: " + data.message +  "</li>");
            }
            else
            {
            $("#messages").append("<li><b>" + data.username + "</b>: " + data.message +  "</li>");
            }
        });

Can someone edit it to make it scroll automatically when new messages are appended to the <ul> in the a <div> tag. NOTE: The id of that <ul> is "messages".

iammithani
  • 108
  • 2
  • 10

1 Answers1

1

Lets assume that your div has id "#div1". Then you can do it like this:

$("#div1").animate({ scrollTop: $('#div1').prop("scrollHeight")}, 1000);
Elman Huseynov
  • 1,127
  • 1
  • 8
  • 18