Created
June 30, 2015 20:24
-
-
Save coryk135/c520d1edcc145cb2cc26 to your computer and use it in GitHub Desktop.
Firebase realtime chat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<script src='https://cdn.firebase.com/v0/firebase-debug.js'></script> | |
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> | |
<link rel='stylesheet' type='text/css' href='/resources/tutorial/css/example.css'> | |
</head> | |
<body> | |
<div id='messagesDiv'></div> | |
<div id='temp'></div> | |
<input type='text' id='nameInput' placeholder='Name'> | |
<input type='text' id='messageInput' placeholder='Message'> | |
<script> | |
var tid = null; | |
var myDataRef = new Firebase('https://i8dx5bc88a9.firebaseio-demo.com/'); | |
$('#messageInput').keyup(function (e) { | |
if (e.keyCode == 13) { | |
var name = $('#nameInput').val(); | |
var text = $('#messageInput').val(); | |
myDataRef.child("list").push({name: name, text: text}); | |
$('#messageInput').val(''); | |
} | |
clearTimeout(tid) | |
tid = setTimeout(updateTempString, 300) | |
}); | |
myDataRef.child("list").on('child_added', function(snapshot) { | |
debugger; | |
var message = snapshot.val(); | |
displayChatMessage(message.name, message.text); | |
}); | |
function displayChatMessage(name, text) { | |
$('<div/>').text(text).prepend($('<strong/>').text(name+': ')).appendTo($('#messagesDiv')); | |
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight; | |
}; | |
function updateTempString(){ | |
var o = { | |
name: $('#nameInput').val(), | |
text: $('#messageInput').val() | |
} | |
myDataRef.child("temp").set(o, function(){ | |
debugger; | |
}) | |
} | |
myDataRef.child("temp").on('value', function(snapshot) { | |
debugger; | |
var message = snapshot.val(); | |
if(message.text){ | |
$('#temp').html($('<em/>').text(message.name+': '+message.text)); | |
} else { | |
$('#temp').html(''); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment