-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode2.js
More file actions
55 lines (47 loc) · 1.73 KB
/
Copy pathcode2.js
File metadata and controls
55 lines (47 loc) · 1.73 KB
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
var myId;
// Get the input field
var input = document.getElementById("messageBox");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("send").click();
}
});
(function() {
const sendBtn = document.querySelector('#send');
const messages = document.querySelector('#messages');
const messageBox = document.querySelector('#messageBox');
let ws;
function showMessage(message) {
messages.textContent += `\n\n${message}`;
messages.scrollTop = messages.scrollHeight;
messageBox.value = '';
}
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('Connection opened!');
}
ws.onmessage = ({ data }) => showMessage(data);
ws.onclose = function() {
ws = null;
}
}
sendBtn.onclick = function() {
if (!ws || ws.readyState !== WebSocket.OPEN) {
showMessage("No WebSocket connection :(");
return;
}
ws.send(messageBox.value);
showMessage(messageBox.value);
}
init();
})();