-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
85 lines (62 loc) · 2.58 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const msgForm = document.body.querySelector("#send-msg");
const msgInput = document.body.querySelector("#send-msg input");
const conversation = document.body.querySelector("#conversation");
const wrapper = document.body.querySelector(".wrapper");
const pseudoForm = document.body.querySelector("#pseudo-choice");
const pseudoInput = document.body.querySelector("#pseudo-choice input");
const pseudoLabel = document.body.querySelector("#pseudo-label");
const socket = io();
// si page d'accueil
if (window.location.pathname == "/") {
pseudoInput.focus();
// fonction choix pseudo
pseudoForm.addEventListener("submit", (e) => {
e.preventDefault();
console.log("hello ", pseudoInput.value);
if (pseudoInput.value == "") {
pseudoLabel.innerHTML += "!";
return;
}
localStorage.setItem("pseudo", pseudoInput.value);
localStorage.setItem("color", getRandomColor());
document.location.href = "/chat";
})
}
// si page du chat
if (document.location.pathname == "/chat") {
socket.emit("new", {pseudo: localStorage.pseudo, color: localStorage.color});
console.log("c tipar", localStorage.pseudo)
// positionne directement le curseur dans l'input
// au chargement de la page
msgInput.focus();
// fonction envoi message
msgForm.addEventListener("submit", (e) => {
e.preventDefault();
console.log(msgInput.value);
msgInput.focus();
socket.emit("chat message", {pseudo: localStorage.pseudo, color: localStorage.color, msg: msgInput.value});
msgInput.value = "";
console.log("xx", wrapper.scrollTop);
return false;
})
socket.on("new", function (data) {
console.log("???")
conversation.innerHTML += `<li><span class="dot" style="color: ${data.color}">⬤ </span><span class="pseudo">${data.pseudo}</span><span class="info"> a rejoint le chat !</span></li>`
})
socket.on("disconnect", function (data) {
conversation.innerHTML += `<li><span class="info" >Quelqu'un est parti en catimini...</li>`
})
// fonction imprime messages envoyés
socket.on("chat message", function (data) {
conversation.innerHTML += `<li><span class="dot" style="color: ${data.color}">⬤ </span><span class="pseudo" >${data.pseudo}:</span> ${data.msg}</li>`
wrapper.scrollTop = wrapper.scrollHeight;
})
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}