-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
58 lines (43 loc) · 1.06 KB
/
client.js
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
const socket= io()
let username;
let textarea=document.querySelector('#textarea')
let messageArea=document.querySelector('.message_area')
do{
username = prompt('Please enter your name: ')
}while(!username)
textarea.addEventListener('keyup', (e) =>{
if(e.key==='Enter'){
sendMessage(e.target.value)
}
})
function sendMessage(message) {
let msg= {
user: username,
message: message.trim()
}
// Apppend
appendMessage(msg,'outgoing')
textarea.value=''
scrollToBottom()
// send to server
socket.emit('message',msg)
}
function appendMessage(msg,type){
let mainDiv= document.createElement('div')
let className= type
mainDiv.classList.add(className,'message')
let markup = `
<h4>${msg.user}</h4>
<p>${msg.message}</p>
`
mainDiv.innerHTML = markup
messageArea.appendChild(mainDiv)
}
// Receive
socket.on('message',(msg) => {
appendMessage(msg,'incoming')
scrollToBottom()
})
function scrollToBottom(){
messageArea.scrollTop = messageArea.scrollHeight
}