Thursday, 1 June 2017

How do I scroll to the bottom of a dynamic ul to which I append data [using jquery, socket.io in code]

I have tried various failed methods for these by other similar questions. Hopefully, y'all can help me. I need help in the part where socket receives an event. Please comment if you require any more details from me

  <body>
    <ul id="messages"></ul>
    <form id="sendform" action="">
      <input id="m" autocomplete="on" /><button>Send</button>
    </form>

        <script src="/socket.io/socket.io.js"></script>
        <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
        <script>
            $(function(){
                var socket = io();
    //          var ready = false;
                var nick;
                while(nick=='' || nick==null)
                    nick = prompt('Enter nick : ');

                socket.emit("join", nick);

                $('#m').focus();
            $("#sendform").submit(function(){
                    if($('#m').val()=='')
                        return false;
              socket.emit('chat message',$('#m').val());
                    $('#m').val('');
              return false;
            });

                socket.on("update",function(msg){
                    $('#messages').append('<li id="update" >'+ msg);
                });
                socket.on('chat message', function(nick,msg){
                    $('#messages').append("<li> <strong>" + nick + "</strong> : " + msg)  ;
                        $('ul, html').css("scrollTop", $("#messages li:last").offset().top);
                });
            });

        </script>



via Akash Joshi

No comments:

Post a Comment