sending messages to the server from websockets works
[mudsync.git] / data / web-static / js / mudsync.js
index f66a9477ca53597bf601502c17ce72b82b159149..1a08b47178142d7b148cc02362ebc5c4801efa9c 100644 (file)
 
 function displayMessage(data) {
     var new_entry = document.createElement("div");
-    new_entry.setAttribute("class", "stream-entry");
     var new_text = document.createTextNode(data);
+    var stream_metabox = document.getElementById("stream-metabox");
+    var should_scroll = false;
+    if(stream_metabox.scrollTop === (stream_metabox.scrollHeight
+                                     - stream_metabox.offsetHeight)) {
+        should_scroll = true;
+    }
+    document.getElementById("main-input").value = "";
+    new_entry.setAttribute("class", "stream-entry");
     new_entry.appendChild(new_text);
     document.getElementById("stream").appendChild(new_entry);
+    if (should_scroll) {
+        stream_metabox.scrollTop = stream_metabox.scrollHeight;
+    }
 }
 
 function installWebsocket() {
@@ -39,8 +49,25 @@ function installWebsocket() {
     ws.onclose = function () {
         console.log("closed websocket");
     };
+    installUIHooks(ws);
+}
+
+function installUIHooks(ws) {
+    var input = document.getElementById("main-input");
+    input.onkeypress = function(e) {
+        if (!e) e = window.event;
+        var keyCode = e.keyCode || e.which;
+        if (keyCode == '13') {
+            sendMessageToServer(ws, input.value);
+        }
+    }
 }
 
+function sendMessageToServer(ws, data) {
+    ws.send(data);
+}
+
+
 window.onload = function () {
     installWebsocket();
 }