-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
114 lines (100 loc) · 2.38 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<!DOCTYPE html>
<html>
<head>
<title>
A chat app with node.js and socket.io
</title>
<style>
#chat {
height: 400px;
}
#contentWrap {
display: none;
}
#chatWrap {
float : left;
border : 1px #000 solid;
}
.whisper {
color : grey;
}
.error {
color : red;
}
</style>
</head>
<body>
<div id="nickWrap">
<p id="nickError"></p>
<form id="setNick">
<p>Enter nickname:</p>
<input type="text" size="35" id="nickname">
<input type="submit">
</form>
</div>
<div id="contentWrap">
<div id="chatWrap">
<div id="chat"></div>
<form id="send-message">
<input type="text" size="40" id="message">
<input type="submit">
</form>
</div>
<div id="users"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" 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){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
} else {
$nickError.html('That username is already taken! Try again.')
}
});
$nickBox.val('');
});
socket.on('username', function(data){
var html = '';
for(var i = 0; i < data.length; i++){
html += data[i] + '<br>';
}
$users.html(html);
});
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val(),function(data){
$chat.append('<span class="error">' + data + '<span>');
});
$messageBox.val('');
});
socket.on('load old msgs', function(docs){
for(var i = 0; i < docs.length; i++){
displayChat(docs[i]);
}
});
socket.on('new message', function(data){
displayChat(data);
});
socket.on('whisper', function(data){
$chat.append('<span class="whisper"><b>' + data.nickname + '</b>:' + data.msg + '<span><br>');
});
function displayChat(data){
return $chat.append('<span class="msg"><b>' + data.nickname + '</b>:' + data.msg + '<span><br>');
}
});
</script>
</body>
</html>