Tutorial: Simple Chat

Tips and TricksExamples Simple Chat

Here a simple example on how to create a Simple Chat using [[service]].

  1. Edit a html file in your favorite editor. Here is a boilerplate

    <!DOCTYPE html>
    <title>WebCom chat demo</title>
  2. Include the Webcom javascript library in head section

     <script src='[[siteUrl]]/libjs/latest/webcom.js'></script>
  3. Create HTML markups for a basic chat UI in body section

     <div class="example-chat">
       <header>WebCom chat demo</header>
       <div class='toolbar'>
         <label for="nameInput">Username:</label>
         <input type='text' id='nameInput' placeholder='enter a username...'>
       <ul id='messages'></ul>
         <input type='text' id='messageInput'  placeholder='Type a message...'>
  4. Before body closing tag (</body>), create a <script> section and create a Webcom reference. Next steps write to this <script> section

         var messagesRef = new Webcom('chat');
  5. Register some DOM elements

    var messageField = document.getElementById('messageInput'),
     nameField = document.getElementById('nameInput'),
     messageList = document.getElementById('messages');
  6. Listen for KeyPress events

    // Listen for "enter" pressed
    messageField.addEventListener('keypress', function (e) {
    var msg = messageField.value;
    if (e.keyCode === 13 && msg !== '' ) {
     // Save data
       name: nameField.value, 
       text: msg
     // Clear message field
     messageField.value = '';
  7. Subscribe to every chat message by adding a callback that is triggered every time a child is added to the Webcom reference

// Add a callback that is triggered for each chat message.
messagesRef.on('child_added', function (snapshot) {
  // Get data
  var data = snapshot.val(),
      username = data.name || "anonymous",
      message = data.text;

  // Create message elements and sanitize text
  var messageElement = document.createElement("li"),
      nameElement = document.createElement("strong");

  nameElement.setAttribute('class', 'username');
  nameElement.innerText = username;

  messageElement.innerText = message;
  messageElement.insertBefore(nameElement, messageElement.childNodes[0]);

  // Add message

  // Scroll to bottom message list
  messageList.scrollTop = messageList.scrollHeight;

For styles, create a new <style> tag in <head> section and copy/paste CSS content of jsBin CSS tab


    <!-- content of CSS JSBin tab -->


###Complete HTML###

Here is full example in jsBin, test it and modify it as you want !

JS Bin on jsbin.com

Or use our version.

You can access the [[console]] and visualize data exchanged in this base in real time with the account : sandbox@list.orange.com (password : sandbox)

Then access the chatsandbox application and browse data