JSFiddle - React, Tailwind, and code Playground
by oroce
HTML
<div style="height:200px;overflow:auto;">
<ul class="msg-list" style="height:auto;">
</ul>
</div>
<input type="text" class="input-txt" /> <button class="send-btn">SEND</button>
JavaScript
var coordinates = null,
onSuccess = function(e) {
coordinates = e.coords;
},
onError = function(e) {
coordinates = null;
};
navigator.geolocation.watchPosition(onSuccess, onError);
var Chat = function(username) {
this.username = username;
this.connect();
this.ws.addEventListener("message", this.onMessage.bind(this), false);
this.sendBtn = $(".send-btn");
this.inputTxt = $(".input-txt");
this.list = $(".msg-list");
var self = this;
this.sendBtn.on("click", function() {
self.send();
});
this.inputTxt.on("keydown", function(e) {
if (e.which === 13) {
self.send()
return false;
}
});
navigator.geolocation.watchPosition(function(e) {
self.coords = [e.coords.latitude, e.coords.longitude];
}, function() {
self.coords = null;
});
};
Chat.prototype.connect = function() {
this.ws = new WebSocket("ws://localhost:3200");
};
Chat.prototype.send = function(msg) {
var msg = this.inputTxt.val();
this.inputTxt.val("");
this.ws.send(
JSON.stringify({
coords: this.coords,
msg: msg,
from: this.username
}));
};
Chat.prototype.onMessage = function(e) {
var message = JSON.parse(e.data);
this.list.append("<li>" + message.from + ": " + message.msg + "(" + message.date + ") - " + (message.address || "") + "</li>");
};
window.chat = new Chat("robi")