-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
95 lines (77 loc) · 2.8 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
<!DOCTYPE html>
<html>
<head>
<title>Chat APP</title>
<link rel="stylesheet" href="main.css" type="text/css" />
</head>
<body>
<div class="chat">
<input type="text" class="chat-name" placeholder="Enter your name." />
<div class="chat-messages"></div>
<textarea placeholder="Type your message"></textarea>
<div class="chat-status">Status:<span>Idle</span></div>
</div>
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
<script>
(function() {
var getNode = function(s) {
return document.querySelector(s);
},
//get required nodes
textarea = getNode('.chat textarea'),
chatName = getNode('.chat-name'),
status = getNode('.chat-status span'),
messages = getNode('.chat-messages'),
statusDefault = status.textContent,
setStatus = function(s) {
status.textContent = s;
if(s !== statusDefault) {
var delay = setTimeout(function() {
setStatus(statusDefault);
clearInterval(delay);
}, 3000);
}
};
try {
var socket = io.connect('http://127.0.0.1:8080');
} catch(e) {
// set status to warn user
console.log("Cant connnect");
}
if(socket !== undefined) {
//listen for output
socket.on('output', function(data) {
if(data.length) {
for(var i = 0; i<data.length; ++i) {
var message = document.createElement('div');
message.setAttribute('class', 'chat-message');
message.textContent = data[i].name + ': ' + data[i].message;
messages.appendChild(message);
messages.insertBefore(message, messages.firstChild);
}
}
});
//listen for status
socket.on('status', function(data) {
setStatus((typeof data === 'object') ? data.message : data);
if(data.clear == true) {
textarea.value = "";
}
});
//listen for keydown
textarea.addEventListener('keydown', function(event) {
var self = this,
name = chatName.value;
if(event.which === 13 && event.shiftKey === false) {
socket.emit('input', {
name: name,
message: self.value
});
event.preventDefault();
}
});
}
})();
</script>
</body>
</html>