-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex-app.html
96 lines (85 loc) · 2.37 KB
/
index-app.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<!DOCTYPE html>
<html>
<head>
<title>Chat with socket.io and node.js</title>
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<div id="nickWrap">
<p>Username:</p>
<p id="nickError"></p>
<form id="setNick">
<input size="35" id="nickname"></input>
<input type="submit"></input>
</form>
</div>
<div id="contentWrap">
<div id="chatWrap">
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
</div>
<div id="users"></div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $nickForm = $('#setNick');
var $nickError = $('#nickError');
var $nickBox = $('#nickname');
var $users = $('#users');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$nickForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $nickBox.val(), function(data){
//respond arrives to client
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
} else {
$nickError.html('That username is already taken, try again!');
}
});
$nickBox.val('');
});
//displaying the usernames' array
socket.on('usernames', function(data){
var html = '';
for (var i = 0; i < data.length; i++) {
html += data[i] + '<br/>';
}
$users.html(html);
});
//every time the submit button is pressed
$messageForm.submit(function(e){
//prevent the default refresh of the page
e.preventDefault();
/* Send it to the server
socket.emit()
name the event: send message
---data we are sending--- IMPORTANT ---
*/
socket.emit('send message', $messageBox.val(), function(data){
$chat.append('<span class="error">'+data+'</span>');
});
//empty the input box
$messageBox.val('');
});
//receive the message on the client side
socket.on('new message', function(data){
//handle the data received
$chat.append('<span class="msg"><b>'+ data.nick + ": </b>"+ data.msg+"<br/></span>");
});
socket.on('whisper', function(data){
$chat.append('<span class="whisper"><b>'+ data.nick + ": </b>"+ data.msg+"<br/></span>");
});
});
</script>
</body>
</html>