Speed up development with full-stack environments for every branch.

Learn More

Firebase Chat Example [JavaScript]

2754 Runs 6701 Views 2401 Copies


praful 60

published 4 years ago

  <title>Firebase Chat Example</title>
  <script type="text/javascript" src="https://cdn.firebase.com/v0/firebase.js"></script>
  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
  <link rel="stylesheet" type="text/css" href="https://www.firebase.com/css/example.css">
<div id='messagesDiv'></div>
<input type='text' id='nameInput' placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message...'>
<script type='text/javascript'>

  // Get a reference to the root of the chat data.
  var messagesRef = new Firebase('https://chat-example.firebaseio-demo.com/');

  // When the user presses enter on the message input, write the message to firebase.
  $('#messageInput').keypress(function (e) {
    if (e.keyCode == 13) {
      var name = $('#nameInput').val();
      var text = $('#messageInput').val();
      messagesRef.push({name:name, text:text});

  // Add a callback that is triggered for each chat message.
  messagesRef.on('child_added', function (snapshot) {
    var message = snapshot.val();
    $('<div/>').text(message.text).prepend($('<em/>').text(message.name+': ')).appendTo($('#messagesDiv'));
    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).