How to build a live comment feature using JavaScript

build-live-commenting-feature-javascript-header.jpg

Build a web app with live comments using Pusher, NodeJS and Vanilla Javascript.

Introduction

This blog post was written under the Pusher Guest Writer program.

These days Social has become the buzzword and we all want our apps to be the centre of these amazing social conversations. Comments on a post, video, update or any feature of your new app is a great way to add fun & enriching social conversations to your App.

If these conversations can be Realtime, then it’s even better, so in this blog post we will be discussing how we can create a realtime comment feature for our web apps using Pusher with Vanilla Javascript on front end & NodeJS on the backend.

We will call this realtime comment system Flash Comments, which can be re-used for multiple posts/features in your app and can generate amazing conversations in real time. Only basic HTML, CSS & JS knowledge is required to follow through this blog post. Our app will look something like this:

Sections

  • Brief Introduction to Pusher
  • Signing Up with Pusher
  • NodeJS & Express App for exposing a Comment Creation API & trigger Pusher Event
  • Front End using Vanilla JS subscribing to Channel

** Skip the first two sections, if you have already signed up with Pusher.

Brief Introduction to Pusher

Pusher is an amazing platform which abstracts the complexities of implementing a Realtime system on our own using Websockets or Long Polling. We can instantly add realtime features to our existing web applications using Pusher as it supports wide variety of SDKs. Integration kits are available for variety of front end libraries like Backbone, React, Angular, jQuery etc and also backend platforms/languages like .NET, Java, Python, Ruby, PHP, GO etc.

Signing up with Pusher

You can create a free account in Pusher at this link <http://pusher.com/signup\>. After you signup and login for the first time, you will be asked to create a new app as seen in the picture below. You will have to fill in some information about your project and also the front end library or backend language you will be building your app with. You also have an option to select the cluster of Pusher based on your users location distribution, I have chosen ap2 (Mumbai, India) as I may be building an app for the India region.

For this particular blog post, we will be selecting Vanilla JS for the front end and NodeJS for the backend as seen in the picture above. This will just show you a set of starter sample codes for these selections, but you can use any integration kit later on with this app.

NodeJS App

Initialising Node Project

You can create a new folder named flash-comments and run the following command at the root of the folder:

npm init

It will ask you bunch of information regarding the app and it will create a new package.json file inside your folder.

We will be using the fairly simple and popular Express framework in Node. Now, we will install the important packages that will be used in our minimal Express app.

npm install -g express body-parser path --save

After installing all required npm modules, now we will create an entry point file for our Node app as server.js inside the root folder. Add the following basic code for a basic HTTP Server to be run using port 9000.

1var express = require('express');
2var path = require('path');
3var bodyParser = require('body-parser');
4
5var app = express();
6
7app.use(bodyParser.json());
8app.use(bodyParser.urlencoded({ extended: false }));
9app.use(express.static(path.join(__dirname, 'public')));
10
11// Error Handler for 404 Pages
12app.use(function(req, res, next) {
13    var error404 = new Error('Route Not Found');
14    error404.status = 404;
15    next(error404);
16});
17
18module.exports = app;
19
20app.listen(9000, function(){
21  console.log('Example app listening on port 9000!')
22});

Pusher has an open source NPM module for NodeJS integrations which we will be using. It provides a set of utility methods to integrate with Pusher APIs using a unique appId, key & a secret. We will first install the pusher npm module using the following command:

npm install pusher --save

Now, we can use require to get the Pusher module and to create a new instance passing an options object with important keys to initialise our integration. For this blog post, I have put random keys; you will have to obtain it for your app from the Pusher dashboard.

1var Pusher = require('pusher');
2
3var pusher = new Pusher({
4  appId: '303964',
5  key: '82XXXXXXXXXXXXXXXXXb5',
6  secret: '7bXXXXXXXXXXXXXXXX9e',
7  cluster: 'ap2',
8  encrypted: true
9});
10
11var app = express();
12...

You will have to replace the appId, key & a secret with values specific to your own app. After this, we will write code for a new API which will be used to create a new comment. This api will expose the route /comment with HTTP POST method and will expect an object for comment with the properties name, email & comment. Add the following code to your server.js file before the app.listen part.

1app.post('/comment', function(req, res){
2  console.log(req.body);
3  var newComment = {
4    name: req.body.name,
5    email: req.body.email,
6    comment: req.body.comment
7  }
8  pusher.trigger('flash-comments', 'new_comment', newComment);
9  res.json({ created: true });
10});

In the above code, we have extracted the data from req.body into a newComment object and then used it to call the trigger method on Pusher instance.

Important Pusher Concepts

Channel

In Pusher, we have a conceptual grouping called Channels and it provides the basic way to filter data in Pusher. A Channel can represent many entities in a real world application. For example: In our comments app, a channel can be comments for a specific Article, video, blog post, photo, live streaming of an event etc.

We would create a new unique channel id for each of these entities to uniquely identify or group data like comments associated with any one of these. Two unique live streaming videos should also have separate Channel so that we can show the respective live comments stream on their respective pages.

So we will create a new unique channel for each entity with their unique id, so for example a Youtube video comments channel can be named comments-youtube-234.

There are three types of channel

  • Public Channel – can be subscribed by anyone who knows the name of the channel.
  • Private Channel – channel which can be subscribed by authorised users only. If the channel name has a private- prefix, it will be regarded as a private channel.
  • Presence Channel – this is a special channel type similar to private as only authorised users can subscribe, where the subscribers list is also maintained and notified to other users also. Channel name should have a prefix presence-

We will use a public channel in our blog post which we are naming as flash-comments but you should ideally use a private channel for commenting systems with unique name for each entity you want to enable commenting feature.

Event

Now, the real data in pusher is transmitted through events which is the primary way of packaging messages. An event can be triggered by a backend or even client in special cases for any particular channel. A channel is required to ensure that your message reaches the intended recipient.

We give a unique name to each event so that we can setup handlers for receiving and processing these event messages at each of our client end who has subscribed to any channel.

Pusher Trigger Method

Now we will understand our server side code for sending an Event to the pusher channel flash-comments.

1...
2pusher.trigger('flash-comments', 'new_comment', newComment);
3...

We are using the .trigger(channel-name,event-name, payload)** to send an **Event from the server whenever the POST API is called for creating a new comment. For the simplicity of this blog post, we will not use any database to save and persist the comments but in a production system, you would be required to store a comment corresponding to a unique entity id like a Youtube Video ID or a Blog Post ID.

Now, we can run our server using node server command. Our web service will be accessible on the URL http://localhost:9000/comment.We can write a POST request using any chrome extension like POSTMan or even CURL to test if it returns { "created":"true" } .

The Curl command to test your POST api will be as follows:

curl -H "Content-Type: appliaction/json" -X POST -d '{"name":"Rahat Khanna","email":"rahat.khanna@yahoo.co.in","comment":"Creating a sample comment"}' http://localhost:9000/comment

Front End using Vanilla JS

Now, we will be writing the most crucial part, the front end code using Vanilla JS. In the front end code we will be developing a Comments box section which would have following 2 features

  • Display all the Live Comments added to the channel with a smooth animation
  • Add new comment to the live comments by hitting the POST Api we have just created

Step 1: Create a folder named public & create an index.html

We have already written code in our server.js to serve static content from public folder, so we will write all our front end code in this folder.

Please create a new folder public and also create an empty index.html for now.

Step 2: Add Boilerplate Code to our index.html

We will be adding some basic boilerplate code to setup the base structure for our web app like Header, Sections where content like video or blog post can be put and also the section which will contain our Flash Comments box.

1<!DOCTYPE>
2<html>
3    <head>
4        <title>Making Social Comments Realtime & Fun with Pusher using Javascript like the Flash</title>
5        <link rel="stylesheet" href="https://unpkg.com/purecss@0.6.2/build/pure-min.css" integrity="sha384-UQiGfs9ICog+LwheBSRCt1o5cbyKIHbwjWscjemyBMT9YCUMZffs6UqUTd0hObXD" crossorigin="anonymous">
6        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:200">
7        <link rel="stylesheet" href="./style.css">
8        <meta name="viewport" content="width=device-width, initial-scale=1.0">
9    </head>
10    <body>
11        <header>
12            <div class="logo">
13                <img src="./assets/pusher-logo.png" />
14            </div>
15        </header>
16        <section>
17            <img class="flash-logo" src="./assets/flash-logo.jpg" />
18            <h2>Flash Comments - Super Fast</h2>
19            <div class="post">
20      <!-- Put here Content like Youtube Video, Blog Post or Live Stream -->
21            </div>
22        </section>
23        <section>
24
25           <div class="flash-comments">
26                <div class="header">
27                    <div><img src="./assets/comments.png"></div>
28                    <div class="text">Comments</div>
29                </div>
30                <form class="pure-form" id="comment-form">
31                    <!-- Here we will put a form to create new comment -->
32                </form>
33                 <div class="comments-list" id="comments-list">
34                    <!-- Here we will display live comments -->
35                </div>
36            </div>
37        </section>
38    </body>
39</html>

Step 3: Create style.css file

Now we will also create a style.css file to contain the important css code for styling our web app and the flash comments component. We will add basic styles to render our skeleton.

1body{
2    margin:0;
3    padding:0;
4    overflow: hidden;
5    font-family: Raleway;
6}
7
8header{
9    background: #2b303b;
10    height: 50px;
11    width:100%;
12    display: flex;
13    color:#fff;
14}
15
16.flash-logo{
17    height:60px;
18    border-radius: 8px;
19    float: left;
20    margin-right: 15px;
21}
22
23
24section{
25    padding: 15px;
26    width:calc(100% - 45px);
27}
28
29.logo img{
30    height: 35px;
31    padding: 6px;
32    margin-left: 20px;
33}
34
35
36.flash-comments{
37    border:1px solid #aeaeae;
38    border-radius: 10px;
39    width:50%;
40    overflow: hidden;
41}
42
43.post{
44    padding-top:10px;
45}
46
47.flash-comments .header{
48    display: flex;
49    padding: 5px 20px;
50    border-bottom: 1px solid #eaeaea;
51}
52
53.flash-comments .header .text{
54    padding-left:15px;
55    line-height: 25px;
56}
57
58.flash-comments .comment{
59    display: flex;
60    border-bottom:1px solid #eaeaea;
61    padding: 4px;
62}

Step 4: Add the Pusher JS Library & create app.js

Now we will add the Pusher Vanilla JS Library available on its CDN to use it to integrate with the Pusher system using plain Javascript code. Please add the following script tag at the end of the body before its closing tag:

1...
2<script type="text/javascript" src="https://js.pusher.com/3.2/pusher.min.js"></script>
3</body>
4...

Also, create a new app.js file where we will be writing all our code and also import the same in our index.html file after the script tag to import Pusher JS file.

1<script type="text/javascript" src="https://js.pusher.com/3.2/pusher.min.js"></script>
2<script type="text/javascript" src="./app.js"></script>
3</body>

In our file app.js now, we will write code to initialise the Pusher instance using the unique client API key we have got from the Pusher dashboard. We will also pass an object specifying the cluster and setting the flag encrypted to true so that all messaging & communication is encrypted. We will also use the pusher.subscribe('channel-name') to listen to all events for a specific channel.

We will create a Javascript IIFE (Immediately Invoking Functions) to create a private scope so that we do not pollute global scope. Please add the following code to app.js file:

1// Using IIFE for Implementing Module Pattern to keep the Local Space for the JS Variables
2(function() {
3    // Enable pusher logging - don't include this in production
4    Pusher.logToConsole = true;
5
6    var serverUrl = "/",
7        comments = [],
8        pusher = new Pusher('82XXXXXXXXXXXXXX5', {
9          cluster: 'ap2',
10          encrypted: true
11        }),
12        // Subscribing to the 'flash-comments' Channel
13        channel = pusher.subscribe('flash-comments');
14
15})();

Step 5: Creating Form for adding new comment

Now, we will create the form controls for letting the user input their name, email and comment text for creating a new comment using our Node API and Pusher. We will add the following HTML code inside the existing form tag to create form.

1<form class="pure-form" id="comment-form">
2  <div class="comment-form">
3      <div class="left-side">
4           <div class="row">
5               <input type="text" required placeholder="enter your name" id="new_comment_name">
6               <input placeholder="enter valid email" required type="email" id="new_comment_email">
7            </div>
8            <div class="row">
9                <textarea placeholder="enter comment text" required id="new_comment_text" rows="3"></textarea>
10            </div>
11      </div>
12     <div class="right-side">
13            <button type="submit" class="button-secondary pure-button">Send Comment</button>
14     </div>
15 </div>
16</form>

In the form code above, we have used HTML5 validations like required & type=email which would not allow user to keep these fields blank or submit an invalid email. These validations will automatically work in most browsers which support HTML5 form validations.

Also, we will be adding the following css to style the form:

1.flash-comments form{
2    margin-bottom: 0px;
3}
4
5.flash-comments .comment-form{
6    display: flex;
7    padding: 6px;
8    border-bottom:1px solid #eaeaea;
9}
10
11.comment-form .left-side{
12    flex: 5;
13    display: flex;
14    flex-direction: column;
15    padding-right: 5px;
16}
17
18.comment-form .left-side .row{
19    flex: 0 auto;
20    display: flex;
21    align-content: center;
22}
23
24.comment-form .left-side .row input{
25    height: 32px;
26    width: 50%;
27}
28
29.comment-form .left-side .row textarea{
30    height: 42px;
31    margin-top:8px;
32}
33
34.comment-form .right-side{
35    flex:1;
36    display: flex;
37    justify-content: center;
38}
39
40.comment-form .right-side button{
41    white-space: pre-wrap;
42}
43
44.comment-form textarea{
45    width:100%;
46}
47
48.button-secondary {
49    background: rgb(66, 184, 221); /* this is a light blue */
50    color: white;
51    border-radius: 4px;
52    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
53}

After building the visual form, now we need to attach an event handler to the Submit event of the form. We will do that using the following code in the app.js file probably at the top after the var declarations:

1var commentForm = document.getElementById('comment-form');
2
3// Adding to Comment Form Submit Event
4commentForm.addEventListener("submit", addNewComment);

Now, we will write the code for implementation of the handler addNewComment with the following code:

1function addNewComment(event){
2      event.preventDefault();
3      var newComment = {
4        "name": document.getElementById('new_comment_name').value,
5        "email": document.getElementById('new_comment_email').value,
6        "comment": document.getElementById('new_comment_text').value
7      }
8
9      var xhr = new XMLHttpRequest();
10      xhr.open("POST", serverUrl+"comment", true);
11      xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
12      xhr.onreadystatechange = function () {
13        if (xhr.readyState != 4 || xhr.status != 200) return;
14
15        // On Success of creating a new Comment
16        console.log("Success: " + xhr.responseText);
17        commentForm.reset();
18      };
19      xhr.send(JSON.stringify(newComment));
20}

We are using native XHR request to make an AJAX request to the Node API. You can use either jQuery Ajax or any framework-specific Ajax method in your app. Now if we run our application, then fill the form and submit it, then we will see a Success: { created: true }message in our browser developer tools console.

Also, we can see the Pusher Dashboard to see the stats about Event Messages sent for any channel.

Step 6: Display List of Comments Received for this Channel

Now, we will bind to the new_comment event on this channel flash-comments so that we can receive any message about new comment creation done from any client in realtime, and we can display all those comments.

We will first add a template for a new comment in our index.html file inside the div tag with id="comments-list".

1<div class="comments-list" id="comments-list">
2    <script id="comment-template" type="text/x-template">
3        <div class="user-icon">
4            <img src="./assets/user.png" />
5        </div>
6        <div class="comment-info">
7            <div class="row">
8                  <div class="name">{{name}}</div>
9                  <div class="email">{{email}}</div>
10             </div>
11             <div class="row">
12                   <div class="text">{{comment}}</div>
13             </div>
14         </div>
15     </script>
16</div>

Now, we will write the Javascript code to bind to the new_comment event on the pusher channel instance we have subscribed. Whenever the new_comment event will be fired, we will take the template innerHTML content and replace the placeholders {{name}}, {{email}} & {{comment}}with the data passed along with the event and append them to the comments-list div element.

1var commentsList = document.getElementById('comments-list'),
2    commentTemplate = document.getElementById('comment-template');
3
4// Binding to Pusher Event on our 'flash-comments' Channel
5channel.bind('new_comment',newCommentReceived);
6
7// New Comment Received Event Handler
8    // We will take the Comment Template, replace placeholders & append to commentsList
9    function newCommentReceived(data){
10      var newCommentHtml = commentTemplate.innerHTML.replace('{{name}}',data.name);
11      newCommentHtml = newCommentHtml.replace('{{email}}',data.email);
12      newCommentHtml = newCommentHtml.replace('{{comment}}',data.comment);
13      var newCommentNode = document.createElement('div');
14      newCommentNode.classList.add('comment');
15      newCommentNode.innerHTML = newCommentHtml;
16      commentsList.appendChild(newCommentNode);
17    }

Using the above code, a new div tag representing the new comment will automatically be created and appended to the comments-list container. We will now add the following css to nicely display the list of comments and also animate whenever a new comment appears on the list.

1.flash-comments .user-icon{
2    flex: 0 80px;
3    display: flex;
4    justify-content: center;
5}
6
7.flash-comments .user-icon img{
8    height:45px;
9}
10
11.flash-comments .comment-info{
12    flex:5;
13}
14
15.flash-comments .comment-info .row{
16    display: flex;
17}
18
19.flash-comments .comment-info .name{
20    color: #000;
21}
22
23.flash-comments .comment-info .email{
24    color: #aeaeae;
25    margin-left: 10px;
26}
27
28.flash-comments .comment-info .text{
29    padding-top:6px;
30    font-size: 13px;
31}
32
33/* CSS Code for Animating Comment Element */
34.flash-comments .comment{
35  animation: animationFrames ease 1s;
36  animation-iteration-count: 1;
37  transform-origin: 50% 50%;
38  animation-fill-mode:forwards; /*when the spec is finished*/
39  -webkit-animation: animationFrames ease 1s;
40  -webkit-animation-iteration-count: 1;
41  -webkit-transform-origin: 50% 50%;
42  -webkit-animation-fill-mode:forwards; /*Chrome 16+, Safari 4+*/ 
43  -moz-animation: animationFrames ease 1s;
44  -moz-animation-iteration-count: 1;
45  -moz-transform-origin: 50% 50%;
46  -moz-animation-fill-mode:forwards; /*FF 5+*/
47  -o-animation: animationFrames ease 1s;
48  -o-animation-iteration-count: 1;
49  -o-transform-origin: 50% 50%;
50  -o-animation-fill-mode:forwards; /*Not implemented yet*/
51  -ms-animation: animationFrames ease 1s;
52  -ms-animation-iteration-count: 1;
53  -ms-transform-origin: 50% 50%;
54  -ms-animation-fill-mode:forwards; /*IE 10+*/
55}
56
57@keyframes animationFrames{
58  0% {
59    opacity:0;
60    transform:  translate(-1500px,0px)  ;
61  }
62  60% {
63    opacity:1;
64    transform:  translate(30px,0px)  ;
65  }
66  80% {
67    transform:  translate(-10px,0px)  ;
68  }
69  100% {
70    opacity:1;
71    transform:  translate(0px,0px)  ;
72  }
73}
74
75@-moz-keyframes animationFrames{
76  0% {
77    opacity:0;
78    -moz-transform:  translate(-1500px,0px)  ;
79  }
80  60% {
81    opacity:1;
82    -moz-transform:  translate(30px,0px)  ;
83  }
84  80% {
85    -moz-transform:  translate(-10px,0px)  ;
86  }
87  100% {
88    opacity:1;
89    -moz-transform:  translate(0px,0px)  ;
90  }
91}
92
93@-webkit-keyframes animationFrames {
94  0% {
95    opacity:0;
96    -webkit-transform:  translate(-1500px,0px)  ;
97  }
98  60% {
99    opacity:1;
100    -webkit-transform:  translate(30px,0px)  ;
101  }
102  80% {
103    -webkit-transform:  translate(-10px,0px)  ;
104  }
105  100% {
106    opacity:1;
107    -webkit-transform:  translate(0px,0px)  ;
108  }
109}
110
111@-o-keyframes animationFrames {
112  0% {
113    opacity:0;
114    -o-transform:  translate(-1500px,0px)  ;
115  }
116  60% {
117    opacity:1;
118    -o-transform:  translate(30px,0px)  ;
119  }
120  80% {
121    -o-transform:  translate(-10px,0px)  ;
122  }
123  100% {
124    opacity:1;
125    -o-transform:  translate(0px,0px)  ;
126  }
127}
128
129@-ms-keyframes animationFrames {
130  0% {
131    opacity:0;
132    -ms-transform:  translate(-1500px,0px)  ;
133  }
134  60% {
135    opacity:1;
136    -ms-transform:  translate(30px,0px)  ;
137  }
138  80% {
139    -ms-transform:  translate(-10px,0px)  ;
140  }
141  100% {
142    opacity:1;
143    -ms-transform:  translate(0px,0px)  ;
144  }
145}

Now, you can run the app we have built, either in 2 different browsers or one in normal browser and the other in incognito window, and add multiple comments. We can see that the live comments will be added in realtime with a smooth animation.

The complete code for this tutorial is available on this Github link <https://github.com/mappmechanic/flash-comments\>.

Conclusion

We have built a nice web app with live comment feature using Pusher, NodeJS and Vanilla Javascript. We can use this component with any of our applications and enable live comments for variety of social entities like Videos, Blog Post, Polls, Articles and live streams.

We have used the NodeJS server to create a REST API to get a new comment and then trigger a Pusher event on a specific channel. For any real world application, we can take a unique id for each entity and use a unique channel name for any entity. In a production scenario we can also store the comments in a persistent storage and then later retrieve them.

We have also created a Front End app, which will connect to the Pusher API using pusher-js library. We have created a form to hit the Node API which will trigger new_comment event. Comments are displayed in realtime with an animation using the bind method on the channel instance.