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

Learn More

Firebase Chat Example [JavaScript]

2413 Runs 5793 Views 2023 Copies
Saved

Saved

praful 60

praful
published 3 years ago

<html>
<head>
  <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">
</head>
<body>
<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});
      $('#messageInput').val('');
    }
  });

  // 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;
  });
</script>
</body>
</html>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).