Getting Started with jQuery (Part 5): Building a Real-Time Frontend App

In this final segment of our jQuery tutorial series, we will implement a simple instant messaging app that allows multiple users to chat together at the same time. We will also extend our app to allow for advanced functionality such as the ability to send private messages to another user. 

This tutorial will make use of all the knowledge that you have learned previously in our previous tutorials in this series. If you need a recap, you can refer to the links as follows:

What Is a Real-Time App?

  • What if I tell you that you have used a real-time app before on your phone? 
  • Every day, when you are browsing through Instagram, Facebook or Youtube, did you notice that whenever there is a new update, you will get a small notification in the app? This notification is near-instant, and you are kept up to date on all the new content that has just arrived without reloading the app.
  • Similarly, a real-time web app involves a web application that allows information to be pushed to it by a server instead of it checking for updates periodically. This means that the web application listens for events that are fired from the server and responds accordingly, such as notifying the viewer or updating the interface. This is in contrast to a non-real time web application that constantly polls a server API for updates. (If you are unable what a server API is, do visit our Part 4 tutorial).

A Real-Time Server

  • To implement a real-time web application, we need a server that can accept and push messages that are sent from our application. One of the popular and easy to use push service is Pusher. On the Pusher website, the service is all about “powering real-time experiences in all your apps”. Pusher has ready-made libraries that we can use in our jQuery code to quickly and easily implement real-time functionality which we will leverage on for our instant messaging web app.

Signing up an Account on Pusher

  • To start, sign up for an account at Pusher. Click on the Sign-Up button on the website and fill in your login information. After you have successfully signed up, Pusher will prompt you to create an app. Pusher issues unique keys for each of the app you will be to connect to its service. The pop-up screen will look like this.

  • Fill in the information in the form:
    1. Name your app – “RealTimeChat“.
    2. Select a cluster – leave it at the default selected value.
    3. Choose your tech stack – select the jQuery icon.
    4. Click on “Create my app“.
  • Pusher will now generate your unique app keys, which we will use later to link your web application to Pusher services and also some sample code that you can refer to which can be included in your application.
  • We will not use the sample code that Pusher has displayed and will instead re-implement our custom code to connect step by step so you will be able to understand better what’s going on and with that knowledge, be able to implement other applications by yourself in future.

What Will We Be Building?

  • We will be building a web-based instant messaging application. This messaging application will allow multiple parties to join a common chat room and be able to see each other’s chat messages. There will also be special commands to join or leave the chat room and a user can see who is in the chat room by doing a “list” command. 
  • We will also implement the ability to direct message to another user. When a user sends a direct message to another user in the chat room, only the recipient of the direct message will be able to see the message in their chat window.
  • As with all instant messaging applications, any messages sent to the chat room should appear immediately in the user’s chat window.

Create Our Skeleton HTML 

  • First, let’s code a simple interface which allows the user to view all the posted messages and a small input box which allows the user to add his chat message. 
  • Our HTML body will look as follows.

  • We will also style our HTML like so.

  • This will give us a simple chat interface which looks like this.

  • The message panel will display all the chat messages that are sent to the main chat room and since our CSS has the “overflow-y” option set, the scrollbar will turn active when the number of messages exceeds the height of the message panel box. 

Define the Functionality of Our App

  • Next, we are going to define some of the functionality which we want in our instant messaging application. Below are the 4 major functions we will implement together in this tutorial.
JOIN command
  • To join the chat room, a user should type a “/join (name)” command. The “name” variable will indicate the nickname that he wishes to use during the chat. When a user joins a chat room, his nickname should be broadcasted on the main chat room to indicate that he has joined the chat.
LEAVE command
  • If a user wishes to leave the chat room, the user should enter a “/leave” command. This event will be broadcasted on the main chat room to tell everyone the user is leaving. 
Sending Chats
  • Of course, in an instant messaging application, the basic functionality is the ability for any users to send messages on the main chat room and receive messages as soon as it is submitted.
MSG command
  • To support direct messages where a user can send a private message to another user on the chat room, we will need to implement a “/msg (name)” command. The name will refer to the name of the destination recipient whom a user wants to send a private message.

Pro-Tip:

Professional developers usually prepare a document to state the functionality of the application, similar to what we have done above, before starting to code. This document is typically called the “Functional Specification“. The document states what functions the application should have, what kind of users will be using it and if it interfaces with other external systems. You can also see these functional specifications as a kind of blueprint to help you communicate and clarify your idea about the application before you build it.

Note for JSFiddle Users: Setting up Your Environment

  • For users who are following this tutorial in the JSFiddle environment, you will need to add the Pusher JavaScript library to use the service.
    1. In the JSFiddle window, click on “URL” beside Resources on the left navigation bar. 
    2. Type “https://js.pusher.com/5.0/pusher.min.js” into the “JavaScript/CSS URL” input box and press the blue “Plus” button.
  • If added successfully, you should be able to see a “pusher.min.js” label appearing on the left navigation panel.

Implement the JOIN Command

  • Now that we have our HTML and CSS ready and our Pusher library imported, we are ready to start our jQuery coding!
  • To implement our JOIN command, we will need jQuery to respond to the event where the user types in “/join (name)” in our text input box. When our code detects this command, it should connect to Pusher and listens for events through a subscription. It is through this subscription that our code will be able to receive new events as it is fired. 
  • Think of a subscription-like a newspaper or a magazine subscription. If you are interested in a particular newspaper, you subscribe to the newspaper service. When there are new newspapers, then the newspaper is delivered or pushed to you.
  • Let’s handle the “/join (name)” command. The code is shown below.

  • The code above gets the input text and assigns it to a variable called “message“. We also introduced a new boolean variable called “isConnected” which we will use later to determine if the current user is joined to the real-time chat.
  • Now that we have own code to handle the “/join” command, we will need to do the following items:
    1. We need to parse the name which follows the “/join” command.
    2. Call the Pusher library to subscribe to events.
    3. Broadcast an email to the main chat room to indicate that the current user has joined the chat room.
  • Let’s add a few variables which enable us to keep our Pusher API keys and also keep track of the state of our application.

  • Next, we will initialize our web application to subscribe to the events pushed to us by the Pusher service. We will also introduce the “join the event” method which will be pushed to us once a user joins the channel. The code below shows how should our code react when the “joinevent” is pushed to our web application.

  • We will put up some helper functions at this point to help us easily display messages in the message panel and also clear the input once the user has done entering data

  • Finally, we need to modify our send button click event to post an AJAX API call to our Pusher server so that it can call the Pusher service to broadcast the JOIN message to everyone connected.

  • Wow, that’s a lot of code written but we have set the foundation of all the commands which we want to implement later. We can now use the “/join (name)” command in our instant messaging app. 
  • In the input box, you can type “/join (name)” to join the channel. When you click on the “Send” button, the instant messaging app will send a POST API call to our Pusher echo server which will, in turn, activate the Pusher server to send a message which will be pushed to all the connected clients. 
  • If it is successful, you will be able to see that the message panel will join that the user has connected after issuing the command.

Adding the LEAVE Command

  • Let’s now implement the LEAVE command. When the user issues the leave command, the system should similarly broadcast that the current user has left the channel and all the connected clients should remove the user from their user list. 
  • The code to handle the leave event that is fired from the server is shown below.

  • We will need to modify the send button event to handle the leave event too.

Let’s Chat!

  • Great job following the tutorial up to this point! 
  • In this section, we will implement chat functionality. When one user sends a message on the chat room, it should appear on everyone’s message panel. Here’s how we can do this.
  • Similar like previous, we need to create an event handler for the “chatevent” when it is fired from the Pusher service.

  • We will append an event handler in our send button event to send a chat message to the server for it to be broadcasted.

  • Now you can test it out using 2 different browser windows and both will receive the same broadcasted message.

Mini-Challenge: Ability to Send Direct Messages

  • We are going to improve our instant messaging application by including the ability to send direct messages to other connected users. When a direct message is sent, only the user who is the recipient will be able to see the message on their screen. The following will need to be implemented:
    1. When a user wants to send a direct message, he will need to type a “/msg (recipientnickname) chatmessage” to send a direct message to the intended recipient.
    2. The server will broadcast a message in the format of “!!recipientnickname!! chat message” with a “dmchat-event” type. 
    3. You will need to handle the “dmchat-event” type as well as parse the recipient nickname that is sent in the chat message.
    4. Display the chat message only to the intended recipient.
  • Do take your time to go through this mini-challenge as it is a combination of all the knowledge that you have picked up in our previous tutorials. 

Mini-Challenge Solution

  • Let’s compare answers! 
  • We need to add a handler in our send button event to handle the “/msg” command.

  • Next, we will need to add an event handler when the server pushes the “dmchat-event” to our application. We will also need to include code to only display the message if the recipient matches the current name that the user is logged on to.

To see the whole solution, you can refer to the completed solution.

Conclusion

  • If you have made it till the end of this tutorial, great job! You can now open multiple browser windows and when one message is sent from one browser window, all the other windows will also receive the same message. Remember to use to “/join” command first so that direct messages can be sent to you too.
  • If you have any other questions, feel free to send me a tweet at @AlvinLoh19 or follow me on Twitter for more tech tips and tutorials. 
CategoriesTags

Related Posts