chat.js
1.51 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
56
"use strict";
const socket = io.connect("http://localhost:3000/", {
transports: ["websocket"],
});
const nickname = document.querySelector("#nickname")
const chatlist = document.querySelector(".chatting-list")
const chatInput = document.querySelector(".chatting-input")
const sendButton = document.querySelector(".send-button")
const displayContainer = document.querySelector(".display-container")
chatInput.addEventListener("keypress", (event)=> {
if(event.keyCode === 13) {
send()
}
})
function send() {
const param = {
name: nickname.value,
msg: chatInput.value
}
socket.emit("chatting", param)
}
sendButton.addEventListener("click", send)
socket.on("chatting", (data)=>{
console.log(data)
const {name, msg, time} = data;
const item = new LiModel(name, msg, time);
item.makeLi()
displayContainer.scrollTo(0, displayContainer.scrollHeight)
})
//console.log(socket);
function LiModel(name, msg, time) {
this.name = name;
this.msg = msg;
this.time = time;
this.makeLi = ()=>{
const li = document.createElement("li");
li.classList.add(nickname.value === this.name ? "sent":"received")
const dom = `<span class="profile">
<span class="user">${this.name}</span>
<img class="image" src="https://placeimg.com/50/50/any" alt="any">
</span>
<span class="message">${this.msg}</span>
<span class="time">${this.time}</span>`;
li.innerHTML = dom;
chatlist.appendChild(li)
}
}