Firebase basic chating

Hello, long not post and now I’m back to post new article again. And now I’m ready to write article again. 😀
And again sorry for bad english, I’m from Indonesian and and my English grades at school are very ugly. But why do I still write in English? Because I want share this article not for Indonesian people, but for every one and I’ve you understand this article. Thank you. 🙂

Ok back to the topic, now I want share how to create basic chating (push chat and reply chat) using firebase. What is firebase? You can learn more at https://www.firebase.com. And now go to code…
First create File HTML and rename file to basic-chat.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Basic Chat Using Firebase</title>
</head>
<body>
    <div class="container">
        <div class="chat-box">
            <label>Firebase Chat Basic</label>
            <div class="chat-content" id="chats"></div>
            
            <div class="footer-bar">
                <div class="input">
                    <textarea rows="2" id="message-text"></textarea>
                </div>
                <div class="button">
                    <button type="button" onclick="sendMessage()">Send</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Now save that code and run in your browser, then you can get result like this:

Then now we must add css code to beauty the look of chat-basic page, so edit basic-chat.html like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Basic Chat Using Firebase</title>
    <style>
        .container {
            width: 100%;
        }
        
        .chat-box {
            width: 50%;
            margin: 0 auto;
            font:normal normal 13px/1.4 Tahoma,Verdana,Sans-Serif;
            border: 1px solid #344150;
            background-color: white;
            -webkit-box-shadow: 1px 1px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 1px 1px 5px rgba(0,0,0,.2);
            box-shadow: 1px 1px 5px rgba(0,0,0,.2);
            padding: 10px;
        }
        
        .chat-box > label {
            text-align: center;
            display:block;
            height:24px;
            line-height:24px;
            background-color:#344150;
            color:white;
            font-weight:bold;
            padding:0 1em 1px;
        }
        
        .chat-content {
            height: 400px;
            max-height: 400px;
            overflow-y: scroll;
        }
        
        .chat-content > p {
            color: white;
            display: table;
            padding: 10px;
            border-radius: 14px;
            margin: 5px;
        }
        
        .chat-content > .sender {
            background-color: #A44848;
            float: right;
            text-align: right;
            clear: both;
        }
        
        .chat-content > .receiver {
            background-color: #000;
            clear: both;
        }
        
        .footer-bar {
            margin-top: 20px;
            width: 100%;
        }
        
        .footer-bar > .input, .footer-bar > .button {
            display: inline-block;
            zoom: 1;
            vertical-align: top;
        }
        
        .footer-bar > .input {
            width: 70%;
        }
        
        .footer-bar > .button {
            width: 30%;
        }
        
        .footer-bar {
            width:100%; font-size: 0;
        }
        
        .input, .button {
            display: inline-block; 
            *display: inline; 
            zoom: 1; 
            vertical-align: top; 
            font-size: 12px;
        }
        
        button {
            padding: 10px 40px;
        }
        
        textarea {
            width: 95%;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-box">
            <label>Firebase Chat Basic</label>
            <div class="chat-content" id="chats"></div>
            
            <div class="footer-bar">
                <div class="input">
                    <textarea rows="2" id="message-text"></textarea>
                </div>
                <div class="button">
                    <button type="button" onclick="sendMessage()">Send</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Then run the code and you can get result like this:

And now is time to action. Haha, first from this example I use firebase demo and firebase demo link is https://s3gxhp4xwtz.firebaseio-demo.com. So if you want use your firebase, you must sign up into firebase and create your account there.
Oke now the first is we must add Firebase library, you can get library by CDN. So now change the code again:

<body>
    <div class="container">
        <div class="chat-box">
            <label>Firebase Chat Basic</label>
            <div class="chat-content" id="chats"></div>
            
            <div class="footer-bar">
                <div class="input">
                    <textarea rows="2" id="message-text"></textarea>
                </div>
                <div class="button">
                    <button type="button" onclick="sendMessage()">Send</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
    <script>
        var ref = new Firebase('https://s3gxhp4xwtz.firebaseio-demo.com/');
                
        window.onload = function() {
            var chatMessage = document.getElementById('chats');
            
            ref.once('value', function(data) {
                data.forEach(function(snap) {
                    var message = snap.val();
                    displayChatMessage(message.text);
                }); 
            });
            
            function displayChatMessage(text) {
                chatMessage.innerHTML = chatMessage.innerHTML + "<p style='color: black'>"+text+"</p>";
            }
        }
    </script>
</body>
</html>

Explanation:

  1. Line 117 is Firebase CDN (library)
  2. Line 119. That code is used to connect or defined my Firebase account (example I use Firebase demo)
  3. Line 121. That code is to run (execute code) from line 122-132 after the page already loaded
  4. Line 122. That code is used to get
    <div class="chat-content" id="chats"></div>
    

    Why? Because we want insert content from firebase to this element

  5. Line 124. That code is used to get once value from ref variable and save value to data variable.
  6. Line 125-127. That code is looping data variable, because variable data is array. If you console.log(data.val()) you can get result like this:
    -ImBnHMmOnndxre8XSkl Object { name="Andrew",  text="Firebase is the greatest!"}
    -ImBnI0WLch7L7ndl6Qd Object { name="Rick Astley",  text="It's never going to let me down."}
    

    So we must foreach(data) and send data to function displayChatMessage(message.text); with parameter is message text.

  7. Line 132. This code is to append message text from firebase to

    element.

For more info how to use firebase, you can learn at this site https://www.firebase.com/docs/web/guide and to get database structrue from this article, open this url https://s3gxhp4xwtz.firebaseio-demo.com/. Now run the code and if no error, you can get result like this:

Then we must change text message desain like real chat. So change this code:

var ref = new Firebase('https://s3gxhp4xwtz.firebaseio-demo.com/');
                 
        window.onload = function() {
            var chatMessage = document.getElementById('chats');
             
            ref.once('value', function(data) {
                data.forEach(function(snap) {
                    var message = snap.val();
                    displayChatMessage(message.text);
                }); 
            });
             
            function displayChatMessage(text) {
                chatMessage.innerHTML = chatMessage.innerHTML + "<p style='color: black'>"+text+"</p>";
            }
        }

To be like this:

var ref = new Firebase('https://s3gxhp4xwtz.firebaseio-demo.com/');
http://localhost/learn/basic-chat.html
                 
        window.onload = function() {
            var chatMessage = document.getElementById('chats');
            var chatToogle = 'receiver';
             
            ref.once('value', function(data) {
                data.forEach(function(snap) {
                    var message = snap.val();
                    displayChatMessage(message.text);
                }); 
            });
             
            function displayChatMessage(text) {
                if(chatToogle == 'receiver') {
                    chatMessage.innerHTML = chatMessage.innerHTML + "<p class='"+chatToogle+"'>"+text+"</p>";
                    chatToogle = 'sender'
                } else {
                    chatMessage.innerHTML = chatMessage.innerHTML + "<p class='"+chatToogle+"'>"+text+"</p>";
                    chatToogle = 'receiver'
                }
            }
        }

Explanation:

  1. Line 124. This code is set default class for tag message text is receiver. Css code for receiver classname is already defined, you can look this code on the top html code:
    .chat-content {
        height: 400px;
        max-height: 400px;
        overflow-y: scroll;
    }
    
    .chat-content > p {
        color: white;
        display: table;
        padding: 10px;
        border-radius: 14px;
        margin: 5px;
    }
    
    .chat-content > .sender {
        background-color: #A44848;
        float: right;
        text-align: right;
        clear: both;
    }
    
    .chat-content > .receiver {
        background-color: #000;
        clear: both;
    }
    
  2. Line 134-140. Is to set (toggle classname) from receiver to sender and vice versa

Run the code and you can get result like this:

And then we now we must add code get message from text input and send to firebase after user click button send. Now change this code:

<div class="container">
        <div class="chat-box">
            <label>Firebase Chat Basic</label>
            <div class="chat-content" id="chats"></div>
            
            <div class="footer-bar">
                <div class="input">
                    <textarea rows="2" id="message-text"></textarea>
                </div>
                <div class="button">
                    <button type="button" onclick="sendMessage()">Send</button>
                </div>
            </div>
        </div>
    </div>

Look at line 111 I add onclick=”sendMessage() function to get click event if user click button send. And don’t forget we must create function sendMessage, so edit again your code to be like this:

<script>
        var ref = new Firebase('https://s3gxhp4xwtz.firebaseio-demo.com/');
        
        function sendMessage() {
            var messageText = document.getElementById('message-text');
            ref.push({
                name: 'Imron Rosdiana',
                text: messageText.value
            });
            messageText.value = "";
        }
        
        window.onload = function() {

Explanation:

  1. Line 122. This function is to get textarea element
  2. Line 123-126. This code is used to save textarea value and name into firebase
    database. If you’re familiar with MySQL, this code should be like this:

    INSERT INTO tablename(name, text) VALUES('Imron Rosdiana', messageText.value);
    
  3. Line 127. This code is used after user click send button, so textarea input already clear (empty) value.

And now run the code and insert Hello value and click button send, so what happen? The result is nothing, but try open this https://s3gxhp4xwtz.firebaseio-demo.com, the data already save into firebase database and you can get result like this:

So how to fix them, change the code to be like this:

<script>
        var ref = new Firebase('https://s3gxhp4xwtz.firebaseio-demo.com/');
        
        function sendMessage() {
            var messageText = document.getElementById('message-text');
            ref.push({
                name: 'Imron Rosdiana',
                text: messageText.value
            });
            messageText.value = "";
        }
        
        window.onload = function() {
            var chatMessage = document.getElementById('chats');
            var firstLoadMessage = false;
            var chatToogle = 'receiver';
            
            ref.once('value', function(data) {
                firstLoadMessage = true;
                data.forEach(function(snap) {
                    var message = snap.val();
                    displayChatMessage(message.text);
                }); 
            });
            
            ref.on('child_added', function(snap) {
                var message = snap.val();
                
                if(!firstLoadMessage) return;
                displayChatMessage(message.text);
            });
            
            function displayChatMessage(text) {
                if(chatToogle == 'receiver') {
                    chatMessage.innerHTML = chatMessage.innerHTML + "<p class='"+chatToogle+"'>"+text+"</p>";
                    chatToogle = 'sender'
                } else {
                    chatMessage.innerHTML = chatMessage.innerHTML + "<p class='"+chatToogle+"'>"+text+"</p>";
                    chatToogle = 'receiver'
                }
            }
        }
    </script>

Explanation:

  1. Line 132. This code is to set default variable firstLoadMessage to false. For what this variable? This variable is used if user first open/running basic-chat.html the code on line from line 135-141 is executed but not from line 142-147. Why? For testing comment on line 145 and run the code, so you can get multiple message like this:
  2. Line 142-147. This code is using Firebase function (on(‘child_added’). So if your insert text and click button send, the message automatic add to your html like the magic. You can see this video for example:

Full code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Basic Chat Using Firebase</title>
    <style>
        .container {
            width: 100%;
        }
        
        .chat-box {
            width: 50%;
            margin: 0 auto;
            font:normal normal 13px/1.4 Tahoma,Verdana,Sans-Serif;
            border: 1px solid #344150;
            background-color: white;
            -webkit-box-shadow: 1px 1px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 1px 1px 5px rgba(0,0,0,.2);
            box-shadow: 1px 1px 5px rgba(0,0,0,.2);
            padding: 10px;
        }
        
        .chat-box > label {
            text-align: center;
            display:block;
            height:24px;
            line-height:24px;
            background-color:#344150;
            color:white;
            font-weight:bold;
            padding:0 1em 1px;
        }
        
        .chat-content {
            height: 400px;
            max-height: 400px;
            overflow-y: scroll;
        }
        
        .chat-content > p {
            color: white;
            display: table;
            padding: 10px;
            border-radius: 14px;
            margin: 5px;
        }
        
        .chat-content > .sender {
            background-color: #A44848;
            float: right;
            text-align: right;
            clear: both;
        }
        
        .chat-content > .receiver {
            background-color: #000;
            clear: both;
        }
        
        .footer-bar {
            margin-top: 20px;
            width: 100%;
        }
        
        .footer-bar > .input, .footer-bar > .button {
            display: inline-block;
            zoom: 1;
            vertical-align: top;
        }
        
        .footer-bar > .input {
            width: 70%;
        }
        
        .footer-bar > .button {
            width: 30%;
        }
        
        .footer-bar {
            width:100%; font-size: 0;
        }
        
        .input, .button {
            display: inline-block; 
            *display: inline; 
            zoom: 1; 
            vertical-align: top; 
            font-size: 12px;
        }
        
        button {
            padding: 10px 40px;
        }
        
        textarea {
            width: 95%;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-box">
            <label>Firebase Chat Basic</label>
            <div class="chat-content" id="chats"></div>
            
            <div class="footer-bar">
                <div class="input">
                    <textarea rows="2" id="message-text"></textarea>
                </div>
                <div class="button">
                    <button type="button" onclick="sendMessage()">Send</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
    <script>
        var ref = new Firebase('https://s3gxhp4xwtz.firebaseio-demo.com/');
        
        function sendMessage() {
            var messageText = document.getElementById('message-text');
            ref.push({
                name: 'Imron Rosdiana',
                text: messageText.value
            });
            messageText.value = "";
        }
        
        window.onload = function() {
            var chatMessage = document.getElementById('chats');
            var firstLoadMessage = false;
            var chatToogle = 'receiver';
            
            ref.once('value', function(data) {
                firstLoadMessage = true;
                data.forEach(function(snap) {
                    var message = snap.val();
                    displayChatMessage(message.text);
                }); 
            });
            
            ref.on('child_added', function(snap) {
                var message = snap.val();
                
                if(!firstLoadMessage) return;
                displayChatMessage(message.text);
            });
            
            function displayChatMessage(text) {
                if(chatToogle == 'receiver') {
                    chatMessage.innerHTML = chatMessage.innerHTML + "<p class='"+chatToogle+"'>"+text+"</p>";
                    chatToogle = 'sender'
                } else {
                    chatMessage.innerHTML = chatMessage.innerHTML + "<p class='"+chatToogle+"'>"+text+"</p>";
                    chatToogle = 'receiver'
                }
            }
        }
    </script>
</body>
</html>

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s