You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.6 KiB

2 years ago
2 years ago
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Socket.IO chat</title>
  5. <style>
  6. body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
  7. #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
  8. #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
  9. #input:focus { outline: none; }
  10. #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }
  11. #messages { list-style-type: none; margin: 0; padding: 0; }
  12. #messages > li { padding: 0.5rem 1rem; }
  13. #messages > li:nth-child(odd) { background: #efefef; }
  14. </style>
  15. </head>
  16. <body>
  17. <ul id="messages"></ul>
  18. <form id="form" action="">
  19. <input id="input" autocomplete="off" /><button>Send</button>
  20. </form>
  21. <script src="/socket.io/socket.io.js"></script>
  22. <script>
  23. var socket = io();
  24. var form = document.getElementById('form');
  25. var input = document.getElementById('input');
  26. form.addEventListener('submit', function(e) {
  27. e.preventDefault();
  28. if (input.value) {
  29. socket.emit('chat message', input.value);
  30. input.value = '';
  31. }
  32. });
  33. socket.on('chat message', function(msg) {
  34. var item = document.createElement('li');
  35. item.textContent = msg;
  36. messages.appendChild(item);
  37. window.scrollTo(0, document.body.scrollHeight);
  38. });
  39. </script>
  40. </body>
  41. </html>