$(function(){ var socket; var last_username; var username_list = []; $(document).ready(function(){ socket = io.connect('http://' + document.domain + ':' + location.port + '/chat'); var current_username = $('#username').val(); socket.on('connect', function() { socket.emit('joined', {}); }); socket.on('status', function(data) { $('#chat').append('
' + sanitizeHTML(data.msg) + '
'); if (data.user && current_username !== data.user) { $('#user-list').append('' + sanitizeHTML(data.msg) + '
'); $('#chat').scrollTop($('#chat')[0].scrollHeight); }); $('#new-message').on('keypress', function(e) { var code = e.keyCode || e.which; if (code == 13) { emitMessage(socket); } }); $('#send-button').on('click', emitMessage); $('#update-username').on('click', function() { var username = $('#username').val(); socket.emit('update_username', {username: username}); }); }); }); var emitMessage = function(socket) { var text = $('#new-message').val(); $('#new-message').val(''); socket.emit('text', {msg: text}); } var sanitizeHTML = function(str) { var temp = document.createElement('span'); temp.textContent = str; return temp.innerHTML; };