title: Instant Chat on Web Application Using Firebase Database JavaScript
body: <p>In my website I am creating a instant messaging service using Firebase data base. I have got the functionality of the chat working so users can send a message to the chat which will display in the display box.</p>
  
  <p>The problem I'm having is, when a new chat is created and users begin a conversation, the messages appear in order of the conversation they're having as they should As seen below:</p>
  
  <p><a href="https://i.stack.imgur.com/GVAcX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GVAcX.png" alt="enter image description here"></a></p>
  
  <p>but when the page is refreshed and the messages are pulled from the database is displays as follows.</p>
  
  <p><a href="https://i.stack.imgur.com/NxXrx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NxXrx.png" alt="enter image description here"></a></p>
  
  <p>My db structure for the chat is as follows:</p>
  
  <p><a href="https://i.stack.imgur.com/58Ao9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/58Ao9.png" alt="enter image description here"></a></p>
  
  <p>And my JS code is for the chat is:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
      // User is signed in.
   var db = firebase.database();
   var currentProperty = localStorage.getItem("prop");
   
   db.ref('addresses/'+currentProperty+'/chat/group').on("child_added", function(data){
    //Set Local Variables
    var message = data.child("message").val();
    var date = data.child("date").val();
    var sender = data.child("uid").val();
    var time = data.child("time").val();
    var who;
    var getCurrentDate = new Date;
    day = getCurrentDate.getDate();
    month = getCurrentDate.getMonth() + 1;          
    year = getCurrentDate.getFullYear();
    var newDate = [day, month, year].join('/');
    var title = document.getElementById("chatTitle");
    db.ref('addresses/'+currentProperty+'/firstLine').once("value", function(snapshot){
     title.innerHTML = "&lt;i class='fas fa-home' style='font-size:150%;margin-right:10px'&gt;&lt;/i&gt;Group chat with all persons involved with " + capitalLetter(snapshot.val());
    });
    
    if(sender == user.uid){who = 'boxCurrent currentUser';}
    else
    {who = 'boxOther otherUser';}
    
    if(date == newDate){date = 'Today'}
    
    db.ref('users/'+sender+'/firstName').on('value', function(data){
     var name = data.val();
     if(who == 'boxCurrent currentUser'){
      var messageD = "&lt;div id='userMessageDisplay' style='width:100%;text-align:end;'&gt;&lt;span class='message-data-time'&gt;"+time+",  "+date+"    &lt;/span&gt;&lt;span id='userName'&gt;"+name+"&lt;/span&gt;&lt;div id='hello' class='"+who+"' style= height:100%;'&gt;"+message+"&lt;/div&gt;&lt;/div&gt;";
     $('#displayBox').append(messageD);
     }
     else{
      var messageD = "&lt;div id='userMessageDisplay' style='width:100%;'&gt;&lt;span class='message-name'&gt;"+name+"&lt;/span&gt;&lt;span class='message-data-time'&gt;    "+time+",  "+date+"&lt;/span&gt;&lt;div id='hello' class='"+who+"' style='width:70%; height:100%;'&gt;"+message+"&lt;/div&gt;&lt;/div&gt;";
     $('#displayBox').append(messageD);
     }
    });
   });
   
   db.ref('addresses/'+currentProperty+'/tenant').orderByKey().once("value", function(snapshot){
    snapshot.forEach(function(child){
      var key = child.key;
      console.log(key);
      db.ref('users/'+key+'/firstName').once("value", function(data){
       var first = data.val();
       var appendFirst = "&lt;li style='padding: 5px 10px 0 10px; height:75px;'&gt;&lt;i class='fas fa-user-circle' style='font-size:400%; float:left;color:#6a6c75;'&gt;&lt;/i&gt;&lt;div class='about' style='height:100%;padding: 10px 0 0 70px;'&gt;&lt;div id='append2"+key+"' class='profileName' style='color:#fff;'&gt;"+first;
       $('#peopleList').append(appendFirst);
  
      });
      db.ref('users/'+key+'/lastName').once("value", function(data){
       var last = data.val();
       var appendLast = " "+last+"&lt;/div&gt;"
       $('#append2'+key).append(appendLast);
      });
      db.ref('users/'+key+'/onlineStatus').once("value", function(data){
       var onlineStatus = data.val();
       console.log(onlineStatus);
       if(onlineStatus == 'Online'){
       var appendStatus = "&lt;div class='status' style='color:#a8aac3;'&gt;&lt;i class='fa fa-circle' online style='color:#86BB71; margin-right:10px;font-size:80%;border:1px solid #fff;border-radius:50%;'&gt;&lt;/i&gt;Online&lt;/div&gt;&lt;/div&gt;&lt;/li&gt;"
       $('#append2'+key).append(appendStatus);
       }
       else{
        appendStatus = "&lt;div class='status' style='color:#a8aac3;'&gt;&lt;i class='fa fa-circle offline' style='color:#E38968;margin-right:10px;font-size:80%;border:1px solid #fff;border-radius:50%;'&gt;&lt;/i&gt;Offline&lt;/div&gt;&lt;/div&gt;&lt;/li&gt;"
        $('#append2'+key).append(appendStatus);
       }
      });
    });
   });
   
    } else {
      // No user is signed in.
   location = 'index.html'
    }
  });
  
  function sendMessage(){
   var theDiv = document.getElementById('displayBox');
   var message = document.getElementById("messageInput").value;
   var currentProperty = localStorage.getItem("prop");
   var user = firebase.auth().currentUser;
   //date
   var date = new Date;
   day = date.getDate();
   month = date.getMonth() + 1;          
   year = date.getFullYear();
   var newDate = [day, month, year].join('/');
   var db = firebase.database();
   //time
   hours = date.getHours(); // =&gt; 9
   mins = date.getMinutes(); // =&gt;  30
   var time = [hours, mins].join(':');
   console.log(time);
   
   var messageDetails = {
    "uid": user.uid,
    "message": message,
    "date": newDate,
    "time": time
    }
    
   if(message == ''){
    document.getElementById("messageInput").style.border = '1px solid red';
   }
   else{
    db.ref('addresses/'+currentProperty+'/chat/group').push(messageDetails).then(function(){
     document.getElementById("messageInput").value = '';
     theDiv.scrollTop = '99999';
    });
   }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Apologies for the long post but does anyone know why when the page is refreshed, the messages are clustered buy the user who sent the message? </p>
  
  <p>Also any solutions to resolved the problem will be extremely helpful.</p>
  
  <p>Thanks in advance.</p>