diff options
| author | Bobby <[email protected]> | 2023-05-15 07:30:20 -0400 |
|---|---|---|
| committer | Bobby <[email protected]> | 2023-05-15 07:30:20 -0400 |
| commit | 394d74b553360a82f803a34205a8df609777fdff (patch) | |
| tree | 8e78eb5214a47eb5fa46d7400cea192ed6b3aa94 /static/js/chat.js | |
| parent | 4cbc1c64b3f5f7bc6f6f9744dd09828d7e79d65d (diff) | |
| download | thatcomputerscientist-394d74b553360a82f803a34205a8df609777fdff.tar.xz thatcomputerscientist-394d74b553360a82f803a34205a8df609777fdff.zip | |
Simple working live chat
Diffstat (limited to 'static/js/chat.js')
| -rw-r--r-- | static/js/chat.js | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/static/js/chat.js b/static/js/chat.js new file mode 100644 index 00000000..45486286 --- /dev/null +++ b/static/js/chat.js @@ -0,0 +1,50 @@ +$(document).ready(function(){ + function createMessageElement(message, username, type) { + var messageElement = document.createElement('div'); + var username = username || 'Anonymous'; + messageElement.classList.add('message'); + switch(type) { + case 'connect': + messageElement.innerHTML = '<span style="color: #a0e9ff;">' + "<b>" + username + "</b>: " + message + '</span>'; + break; + case 'disconnect': + messageElement.innerHTML = '<span style="color: #ff9494;">' + "<b>" + username + "</b>: " + message + '</span>'; + break; + case 'default': + messageElement.innerHTML ="<b>" + username + "</b>: " + message; + break; + } + $('#messages').append(messageElement); + $('#messages').animate({scrollTop: $('#messages').prop("scrollHeight")}, 100); + $('#chatbox-input').val(""); + } + + var protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://'; + var URL = protocol + window.location.host + '/ws/chat/'; + + var ws = new WebSocket(URL); + ws.onopen = function(e) { + createMessageElement('You are now connected to the Chat Server!', 'System', 'connect'); + } + ws.onerror = function(e) { + createMessageElement('Connection to the Chat Server failed!', 'System', 'disconnect'); + } + ws.onclose = function(e) { + createMessageElement('You have been disconnected from the Chat Server!', 'System', 'disconnect'); + } + ws.onmessage = function(e) { + var data = JSON.parse(e.data); + createMessageElement(data['message'].trim(), data['username'], 'default'); + } + + $('#chatbox-input').on('keyup', function(e) { + if (e.keyCode == 13) { + var message = $('#chatbox-input').val(); + ws.send(JSON.stringify({ + 'message': message, + 'username': username + })); + $('#chatbox-input').val(""); + } + }); +});
\ No newline at end of file |
