chat.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const params = new URLSearchParams(window.location.search);
  2. const room = params.get("room");
  3. if (!room) {
  4. alert("No room specified. Redirecting to homepage...");
  5. window.location.href = "/";
  6. }
  7. const socket = new WebSocket(`ws://${location.host}/room?room=${room}`);
  8. socket.onmessage = (event) => {
  9. try {
  10. const data = JSON.parse(event.data);
  11. // Create the container div
  12. const msgContainer = document.createElement("div");
  13. msgContainer.classList.add("message-container");
  14. // Create the username div
  15. const usernameDiv = document.createElement("div");
  16. usernameDiv.classList.add("username");
  17. usernameDiv.textContent = data.name;
  18. // Create the message div
  19. const messageDiv = document.createElement("div");
  20. messageDiv.classList.add("message");
  21. messageDiv.textContent = data.message;
  22. // Append username and message in correct order
  23. msgContainer.appendChild(usernameDiv);
  24. msgContainer.appendChild(messageDiv);
  25. // Append the whole message container to the messages div
  26. document.getElementById("messages").appendChild(msgContainer);
  27. // Auto-scroll
  28. const messagesDiv = document.getElementById("messages");
  29. messagesDiv.scrollTop = messagesDiv.scrollHeight;
  30. } catch (err) {
  31. console.error("Invalid JSON received:", event.data);
  32. }
  33. };
  34. function sendMessage() {
  35. const input = document.getElementById("msg");
  36. if (input.value.trim() !== "") {
  37. socket.send(input.value);
  38. input.value = "";
  39. }
  40. }
  41. document.getElementById("sendBtn").addEventListener("click", sendMessage);
  42. document.getElementById("msg").addEventListener("keyup", function (event) {
  43. if (event.key === "Enter") {
  44. sendMessage();
  45. }
  46. });