From cf7e0630c77b8f0e9660e3e633e10ea3db116387 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Tue, 26 Jul 2022 15:41:36 +0200 Subject: Usernames and exclude sender --- Year_3/Web/chat-socket-io/assets/chat.js | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Year_3/Web/chat-socket-io/assets/chat.js (limited to 'Year_3/Web/chat-socket-io/assets/chat.js') diff --git a/Year_3/Web/chat-socket-io/assets/chat.js b/Year_3/Web/chat-socket-io/assets/chat.js new file mode 100644 index 0000000..2dfdd62 --- /dev/null +++ b/Year_3/Web/chat-socket-io/assets/chat.js @@ -0,0 +1,37 @@ +var form = document.getElementById("form"); +var input = document.getElementById("input"); +const messages = document.getElementById("messages"); + +form.addEventListener("submit", function(e) { + e.preventDefault(); + let value = input.value; + if (value) { + if (value[0] == "/") { + let command = value.split(" "); + if (command.length == 2 && command[0] == "/user") { + socket.emit("set user", command[1]); + } else { + socket.emit("handle error", "Command not found"); + } + } else { + socket.emit("chat message", value); + } + input.value = ""; + } +}); +socket.on("chat message", (msg) => { + var item = document.createElement("li"); + item.textContent = msg; + messages.appendChild(item); + window.scrollTo(0, document.body.scrollHeight); +}); + +socket.on("handle error", (msg) => { + alert(msg); +}); + +socket.on("set user", (username) => { + const userBox = document.getElementById("userBox"); + userBox.innerHTML = username; + alert("Username changed"); +}); -- cgit v1.2.3-18-g5258