-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
42 lines (34 loc) · 1.22 KB
/
script.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
// import { text } from "express"
const socket = io()
const messageContainer = document.getElementById('message-container')
const messageForm = document.getElementById('send-container')
const messageInput = document.getElementById('message-input')
const name = prompt('Please enter a name:')
appendMessage('You joined.', '')
socket.emit('new-user', name)
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`, 'left')
})
socket.on('user-connected', name => {
appendMessage(`${name} joined.`, '')
})
socket.on('user-disconnected', name => {
appendMessage(`${name} left.`, '')
})
messageForm.addEventListener('submit', e =>{
e.preventDefault()
const message = messageInput.value
appendMessage(`You: ${message}`, 'right')
socket.emit('send-chat-message', message)
messageInput.value = ''
})
function appendMessage(message, message_type) {
const messageElement = document.createElement('div')
messageElement.innerText = message
messageElement.setAttribute('class', 'message ' + message_type)
messageContainer.append(messageElement)
if (message_type == 'right') updateScroll();
}
function updateScroll(){
messageContainer.scrollTop = messageContainer.scrollHeight;
}