forked from mheap/socketio-chat-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
73 lines (59 loc) · 1.65 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Socket.io Demo</title>
<style>
.chat-form { display: none; }
</style>
</head>
<body>
<form class="username-form" method="post" action="">
<input type="text" />
<input type="submit" value="Join" />
</form>
<form class="chat-form" method="post" action="">
<div>Hey there, <span id="username">Guest</span></div>
<label>To:</label> <input id="recipient" /><br />
<label>Message: </label><br />
<textarea id="message"></textarea>
<input type="submit" value="Send" />
<ul id="messages">
</ul>
</form>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
// Add a username
$(".username-form").on("submit", function(){
// Tell the server about it
var username = $(this).children("input").val();
socket.emit("add-user", {"username": username});
// Remove this form and show the chat form
$(this).remove();
$("#username").text(username);
chat_form.show();
return false;
});
// Chat form
var chat_form = $(".chat-form");
chat_form.on("submit", function(){
// Send the message to the server
socket.emit("private-message", {
"username": $(this).find("input:first").val(),
"content": $(this).find("textarea").val()
});
// Empty the form
$(this).find("input:first, textarea").val('');
return false;
});
// Whenever we receieve a message, append it to the <ul>
socket.on("add-message", function(data){
$("#messages").append($("<li>", {
"text": data.content
}));
});
</script>
</body>
</html>