text-chat/static/script.js

53 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2022-11-26 15:28:11 +00:00
const input = document.getElementById('input');
const button = document.getElementById('send');
const chat = document.getElementById('chat');
const name = prompt('Enter your name');
const socket = io();
socket.on('connect', () => {
console.log('connected');
socket.emit('name', name);
});
socket.on('text', (text) => {
console.log(text);
2022-12-03 14:56:15 +00:00
addText(text.name, text.text, false);
});
socket.on('join', (name) => {
console.log(`${name} has joined the chat`);
joinedChat(name);
2022-11-26 15:28:11 +00:00
});
button.addEventListener('click', () => {
socket.emit('text', input.value);
2022-12-03 14:56:15 +00:00
addText(name, input.value, true);
input.value = '';
2022-11-26 15:28:11 +00:00
});
2022-12-03 14:56:15 +00:00
function addText(name, text, mine) {
const bubble = document.createElement('div');
const p = document.createElement('p');
p.innerHTML = `<b>${name}:</b> ${text}`;
bubble.classList.add('message-bubble');
if (mine) {
bubble.classList.add('my-message');
}
bubble.appendChild(p);
chat.appendChild(bubble);
}
function joinedChat(name) {
2022-11-26 15:28:11 +00:00
const p = document.createElement('p');
2022-12-03 14:56:15 +00:00
p.innerText = `${name} has joined the chat`;
p.style.fontWeight = 'bold';
p.style.color = 'white';
2022-11-26 15:28:11 +00:00
chat.appendChild(p);
}