Instantly share code, notes, and snippets.

@forcewake /client.js
Last active Dec 22, 2015

Embed
What would you like to do?
$(function() {
var addMessage, connection, content, input, myName, status;
content = $("#content");
input = $("#input");
status = $("#status");
myName = false;
connection = new WebSocket("ws://127.0.0.1:1337");
connection.onopen = function() {
input.removeAttr("disabled");
return status.text("Choose name:");
};
connection.onerror = function(error) {
return content.html($("<p>", {
text: "Sorry, but there's some problem with your " + "connection or the server is down."
}));
};
connection.onmessage = function(message) {
var i, json, _results;
try {
// get json from `message.data`
} catch (e) {
// write to the log
return;
}
if (json.type === "history") {
// while json.data lenght push all messages from history to the content using addMessage
// author | text | time
} else if (json.type === "message") {
// removeAttr disabled from input and add one message to the content using addMessage
} else {
// WAT
}
};
input.keydown(function(e) {
var msg;
if (e.keyCode === 13) {
msg = $(this).val();
if (!msg) return;
connection.send(msg);
$(this).val("");
input.attr("disabled", "disabled");
if (myName === false) myName = msg;
status.text(myName + ": ");
return input.removeAttr("disabled").focus();
}
});
return addMessage = function(author, message, dt) {
return content.prepend("<p><span>" + author + "</span> @ " + +(dt.getHours() < 10 ? "0" + dt.getHours() : dt.getHours()) + ":" + (dt.getMinutes() < 10 ? "0" + dt.getMinutes() : dt.getMinutes()) + ": " + message + "</p>");
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSockets - Simple chat</title>
<style>
* { font-family:tahoma; font-size:12px; padding:0px; margin:0px; }
p { line-height:18px; }
div { width:500px; margin-left:auto; margin-right:auto;}
#content { padding:5px; background:#ddd; border-radius:5px; overflow-y: scroll;
border:1px solid #CCC; margin-top:10px; height: 160px; }
#input { border-radius:2px; border:1px solid #ccc;
margin-top:10px; padding:5px; width:400px; }
#status { width:88px; display:block; float:left; margin-top:15px; }
</style>
</head>
<body>
<div id="content"></div>
<div>
<span id="status">Connecting...</span>
<input type="text" id="input" disabled="disabled" />
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="./client.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment