DEV Community

Cover image for Build a jQuery Chat App
NJOKU SAMSON EBERE for CometChat

Posted on • Originally published at cometchat.com

Build a jQuery Chat App

Introduction

Using a chat application can be very joyous. As we communicate with friends, families, partners and others, we feel a lot better. This is why developers around the world want to add this feature to their applications. But giving such a beautiful experience through writing of code is no child's play. It takes a whole lot of resources to make that happen. But there is good news!

The good news is that this feature has been made available for you by a team that understands your needs. We are talking of the CometChat team.

CometChat can be used to build chat features into our websites or mobile applications. The best part of it is that it supports 10+ languages/platforms. Even jQuery which many developers might feel is outdated is also been supported by CometChat. To prove that, I will be using this tutorial to guide you through building a Chat application using jQuery and CometChat. What we will build will look like this:

Sample App to be built

Before we proceed, allow me to introduce you to CometChat

CometChat

CometChat provides Text chat & video calling solutions for your website and apps to quickly connect your users with each other - patients with doctors, buyers with sellers, teachers with students, gamers, community users, event attendees and more.

For this tutorial, we will be focusing on the CometChat Pro product. It houses highly customizable and easy-to-use SDKs, UI kits, Extensions and Plugins. It also supports more than 10 programming languages and platforms as you may see in the docs here.

With these information, you can see that what you can do with CometChat is only limited to your imagination. It could be solutions on Social community, Marketplace, Dating, On Demand, Edu-Tech, Live Stream and so on. Just Dream and Build with the support of CometChat.

Something really special about CometChat is that you are given a 30 days trial period after which you can decide to continue or not. But why will you not continue with such an awesome gift?

jQuery

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

Prerequisite

This tutorial assumes that you already have basic knowledge of jQuery and firebase. You can catch up with the following links if you are new to those technologies:

  1. jQuery: https://jquery.com/
  2. Firebase: https://firebase.google.com/
  3. Firebase Auth: https://firebase.google.com/docs/auth?authuser=0

Setup CometChat Account and Chat Widget

The first thing we need for this is to create an account with CometChat Pro. So let's get to that...

Create CometChat Pro Account

Follow the next steps to quickly create a CometChat Pro account

CometChat Pro Signup page

You should be on your dashboard like mine below:

CometChat Pro dashboard

Set Up a Chat Widget

The chat widget helps us to configure CometChat in our jQuery website from our CometChat Pro dashboard. So we can control how the Chat functions on our jQuery website from our CometChat dashboard. To do this, we need to create an app in CometChat.

Create an App

  • In your dashboard, click on the Add New App button

Add New App button

  • Fill out the screen that pops up and click on the Add App button

Create App Form

  • You should get this congratulatory popup. Click on the Get Started to be redirected to the dashboard of the app you just created

congratulatory popup

You should now be in that App's dashboard like so:

A CometChat App dashboard

All Good! Your App has been created. You also have 30 days to do all you want for free

Continue Chat Widget Setup

By the left side of the App's dashboard you will find a side menu - a long list of menu items. Do the following:

  • Click on the Chat Widget link

Chat Widget link

  • You should now be presented with a button on the page to add new Chat Widget. Click on the button

Alt Text

And that is all that you need to create a Chat Widget. It has been created automatically on that one click

Chat Widget Configurations

Notice that it contains details for installation by the right side of the screen. We will be using that in a short while.

Build a jQuery Website

At this juncture, we have paused CometChat. Let's build our jQuery website where CometChat will be integrated later. The next steps will show us how to do that:

  • Create a new folder with the name CometChat-jQuery

mkdir CometChat-jQuery

Enter fullscreen mode Exit fullscreen mode
  • Create 5 files inside the folder:

    1. index.html
    2. login.html
    3. init.js
    4. index.js
    5. login.js
  • In the index.html file, enter the following code


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>CometChat jQuery</title>
    <!-- firebase -->
    <script src="https://www.gstatic.com/firebasejs/4.8.2/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.8.2/firebase-auth.js"></script>
  </head>
  <body>
    <div id="main_container" style="display: none">
      <h1>Welcome to CometChat jQuery</h1>
      <button onclick="logout();">logout</button>
    </div>

<!-- jQuery -->
    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"
    ></script>

    <!-- local scripts -->
    <script src="init.js"></script>
    <script src="index.js"></script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode
  • Enter the following code in the login.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>CometChat jQuery Login</title>

    <!-- firebase -->
    <script src="https://www.gstatic.com/firebasejs/4.8.2/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.8.2/firebase-auth.js"></script>
    <script src="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.js"></script>
    <link
      type="text/css"
      rel="stylesheet"
      href="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.css"
    />
  </head>
  <body>
    <!-- The surrounding HTML is left untouched by FirebaseUI.
         Your app may use that space for branding, controls and other customizations.-->
    <h1 style="text-align: center">Login To Chat</h1>
    <div id="firebaseui-auth-container"></div>

<!-- jQuery -->
    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"
    ></script>

    <script src="init.js"></script>
    <script src="login.js"></script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode
  • In the init.js file, enter the following code:

var fireBase = fireBase || firebase;
var hasInit = false;
var config = {
    // ENTER CONFIG HERE
  };

if(!hasInit){
    firebase.initializeApp(config);
    hasInit = true;
}

Enter fullscreen mode Exit fullscreen mode
  • Go to your firebase console
  • Create a project
  • Set the authentication method to email/password
  • Copy firebase configuration
  • Paste it within the init.js file where it reads: // ENTER CONFIG HERE

  • Next, The following code will be in the login.js file


// FirebaseUI config.
var uiConfig = {
  signInSuccessUrl: "index.html",
  signInOptions: [
    // Leave the lines as is for the providers you want to offer your users.
    firebase.auth.EmailAuthProvider.PROVIDER_ID,
  ],
  // Terms of service url.
  tosUrl: "index.html",
};

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start("#firebaseui-auth-container", uiConfig);

Enter fullscreen mode Exit fullscreen mode
  • For the index.js file, enter the following code:

var mainContainer = $("#main_container");

var logout = function () {
  firebase
    .auth()
    .signOut()
    .then(
      function () {
        console.log("success");
        window.location.replace("login.html");
      },
      function () {}
    );
};

var init = function () {
  firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      // User is signed in.
      console.log("stay");
      mainContainer.css("display", "");
    } else {
      // No user is signed in.
      mainContainer.css("display", "none");
      console.log("redirect");
      window.location.replace("login.html");
    }
  });
};

init();

Enter fullscreen mode Exit fullscreen mode

Having done all those work, load the login.html file on your browser and you should have the following page

Login Page

Login a user to get to the index.html page

Index page

If the user has not been signed in before, then you will get the Create Account page to sign up before being redirected to the index.html page

Create Account Page

What the jQuery Website does?
This website is an authentication application. It takes an email and if the email already exist, it requires the password and log the user in. On the other hand, if the email do no exist yet in the database, it asks the user for details to create a new account. The following images demonstrates the application

Create Account
Create Account

Login
Login

Awesome!!!

Integrate CometChat into the jQuery Website

The time has now arrived for us to make the jQuery Website we just built a chat application using CometChat. To make that happen, we will be doing the following:

  1. Initialize CometChat and CometChatWidget
  2. Add the CometChat and CometChatWidget CDN to our html files
  3. Add the CometChat Logout Logic
  4. Determine if a logged in user is a new or returning user
  5. Add the CometChat Login Logic
  6. Add the CometChat Create User Logic

Let's do this!

STEP 1: Initialize CometChat and CometChatWidget

Initializing CometChat and CometChatWidget tells our application that we are ready to use CometChat in our application.

Let's do this by adding the following code in our init.js file:


(function () {
  // cometchat initialization
  var appID = "appID";
  var region = "region ";
  var appSetting = new CometChat.AppSettingsBuilder()
    .subscribePresenceForAllUsers()
    .setRegion(region)
    .build();
  CometChat.init(appID, appSetting).then(
    () => {
      console.log("Initialization completed successfully");
      // You can now call login function.
    },
    (error) => {
      console.log("Initialization failed with error:", error);
      // Check the reason for error and take appropriate action.
    }
  );
})();

// cometchat widget initialization
window.addEventListener("DOMContentLoaded", (event) => {
  CometChatWidget.init({
    appID: "appID",
    appRegion: "region",
    authKey: "authKey",
  }).then(
    (response) => {
      console.log("Initialization (CometChatWidget) completed successfully");
    },
    (error) => {
      console.log("Initialization (CometChatWidget) failed with error:", error);
      //Check the reason for error and take appropriate action.
    }
  );
});

Enter fullscreen mode Exit fullscreen mode

Ensure to replace appID, region and authKey with yours

What's going in the code above?

In the code you just entered, CometChat and CometChatWidget initializations are being automatically invoked once your application loads completely on the browser. The self-invoking function (function{})() ensures that this happens. Now we are ready to use CometChat and CometChatWidget in our application.

STEP2: Add the CometChat and CometChatWidget CDN to our html files

In the index.html

  • Add the following CometChat and CometChatWidget CDN to the head tag just below the firebase CDN:

    <!-- cometchat -->
    <script
      type="text/javascript"
      src="https://unpkg.com/@cometchat-pro/chat@2.3.1/CometChat.js"
    ></script>

    <script
      defer
      src="https://widget-js.cometchat.io/v2/cometchatwidget.js"
    ></script>

Enter fullscreen mode Exit fullscreen mode
  • In the body, just before the script tags, add the following line:

<div id="cometchat"></div>

Enter fullscreen mode Exit fullscreen mode

This is where the CometChat Widget will live. You will see that in a bit

In the login.html

  • Add the following CometChat and CometChatWidget CDN to the head tag just below the firebase CDN:

    <!-- cometchat -->
    <script type="text/javascript" src="https://unpkg.com/@cometchat-pro/chat@2.3.1/CometChat.js"></script>
    <script
      defer
      src="https://widget-js.cometchat.io/v2/cometchatwidget.js"
    ></script>

Enter fullscreen mode Exit fullscreen mode

We will move to index.js file where all the remaining logic will happen. We will be focusing on the init function.

The init function is used to check the authentication status of a user. If the user is authenticated, the user is redirected or allowed to stay on the index.html page


if (user) {
      // User is signed in.
      console.log("stay");
      mainContainer.css("display", "");
    } 

Enter fullscreen mode Exit fullscreen mode

else the user is redirected to the login.html page.

else {
      // No user is signed in.
      mainContainer.css("display", "none");
      console.log("redirect");
      window.location.replace("login.html");
    }
Enter fullscreen mode Exit fullscreen mode

Now, our **CometChat* logic and create user logic will live in the if block above and the logout logic will live in the else block*

Let's Continue!

STEP 3: Add the CometChat Logout Logic

Enter the following code in the else block just before mainContainer.css("display", "none"); line:


CometChat.logout().then(
        () => {
          //Logout completed successfully
          console.log("Logout completed successfully");
        },
        (error) => {
          //Logout failed with exception
          console.log("Logout failed with exception:", { error });
        }
      );

Enter fullscreen mode Exit fullscreen mode

And that is all about the logout. It's that simple!

STEP 4: Determine if a logged in user is a new or returning user

Since the login and create user for our jQuery website isn't clearly separated, it is important to determine if the authenticated user is already existing on our CometChat User db. If the user is not yet registered on our CometChat User db, then we will add such user.

  • Before we proceed collect the user details in the if block of our init function:

// user details
        const userId = user.uid;
        const userName = user.displayName;

Enter fullscreen mode Exit fullscreen mode
  • To determine the authentication status of a user, enter the following code in the if block of our init function:

var UID = "UID";
CometChat.getUser(UID).then(
  user => {
    console.log("User details fetched for user:", user);
    // login and launch chat here in embedded mode
  },
  error => {
    console.log("User details fetching failed with error:", error);
    // create new user, login and launch chat here docked mode
  }
);

Enter fullscreen mode Exit fullscreen mode

How will this code function?

After checking for a user details, if the user exist, the user block returns the user and we can login the user and launch the chat widget here in embedded layout. If on the other hand, the user is new, the error block will return no user and we will use that block to create the new user, login and launch the chat widget here in docked layout. We will talk more about the layouts (embedded and docked) of displaying the chat widget in a bit

We move!

STEP 5: Add the CometChat Login Logic

  • In the response block add the following code to login the user:

CometChatWidget.login({
              uid: userId,
            }).then(
              (response) => {
                console.log("User login successful:", response);
              },
              (error) => {
                console.log("User login failed with error:", error);
                //Check the reason for error and take appropriate action.
              }
            );

Enter fullscreen mode Exit fullscreen mode

Do not forget to replace uid with your own details

  • Once the login is successful, in the then block, enter the following code to launch the CometChat widget:

CometChatWidget.launch({
                    "widgetID": "WIDGET_ID",
                    "target": "#cometchat",
                    "roundedCorners": "true",
                    "height": "600px",
                    "width": "800px",
                    "defaultID": 'superhero1', //default UID (user) or GUID (group) to show,
                    "defaultType": 'user' //user or group
                });

Enter fullscreen mode Exit fullscreen mode

Do not forget to replace WIDGET_ID with your own details

Thumbs Up!!! You can now login an existing user into CometChat. They can also chat with the "friends" already existing in the database.

We are proceeding to the Create User logic

STEP 6: Add the CometChat Create User Logic

Now, let's get back to when we determined if a user already exist in STEP 4. We want to work on the error block (That is when the user do not already exist in our CometChat database).

  • Add the following code in the error block to Create a new User:

let apiKey = "API_KEY";
var uid = userId;
var name = userDisplayName;

var user = new CometChat.User(uid);

user.setName(name);

CometChat.createUser(user, apiKey).then(
    user => {
        console.log("user created", user);
    },error => {
        console.log("error", error);
    }
)

Enter fullscreen mode Exit fullscreen mode

Do not forget to replace apiKey, uid and name with your own details

  • Having successfully created that user, let's login and launch the CometChat Widget in docked mode. Enter the following code in the user block above:

CometChatWidget.login({
                "uid": "UID"
            }).then(response => {
                CometChatWidget.launch({
                    "widgetID": "WIDGET_ID",
                    "docked": "true",
                    "alignment": "left", //left or right
                    "roundedCorners": "true",
                    "height": "450px",
                    "width": "400px",
                    "defaultID": 'superhero1', //default UID (user) or GUID (group) to show,
                    "defaultType": 'user' //user or group
                });
            }, error => {
                console.log("User login failed with error:", error);
                //Check the reason for error and take appropriate action.
            });

Enter fullscreen mode Exit fullscreen mode

Do not forget to replace WIDGET_ID and uid with your own details

That is it with the application!!! We can now register new users who are joining our app. Isn't that awesome?

Test the app and see for yourself. You can follow the progress of the test via your browser's console. See mine below:

New User
New User redirected to the docked view or mode after login

Returning User
New User redirected to the docked view or mode after login

If you check the users in your dashboard, you should see a new user added like mine below:

Alt Text

Embedded Layout vs Docked Layout

CometChat Widget can be displayed in styles. This can be done in two (2) ways:

  1. Docked Layout
  2. Embedded Layout

Docked Layout

This is the floating chat that appears on the pages of a website. You will notice that a new user is redirected to such a chat when logged in for the first time to the app we just created.

Docked Layout with a toggle button

Notice the toggle button used to remove or bring up the chat widget

Embedded Layout

The Embedded Layout is static. It is not toggled by a button like the Docked Layout. You will notice that a returning user is redirected to such a chat when logged in after the first time to the app we just created.

Embedded Layout

Notice that it is embedded on the page and can't be toggled

CometChat Widget Customization

Let's now talk more about the chat widget. We created that widget so that we can control the chat on our website from our CometChat dashboard. So we will need to go back to the chat widget dashboard and see how to make some adjustments.

Chat Widget sections for customization

Notice that we have switched from installation to customization in section 3

This is where you customize the Chat widget to look and feel as you desire. The part labelled 1 represent the sidebar and navigation and the part labelled 2 represent the main body of the chat. When you click either of those sections, the settings are displayed in section 3 (Customization) and you can then make needed changes. There is also the general settings - we can change the color of the toggle button for the docked chat layout there.

Let's make a few changes to our chat widget

  • Allow users to text chat each other
    1. Click on the section 2 of our chat widget
    2. Click on the customization tab in section 3
    3. Click on Messages accordion tab
    4. Click on Send a Message
    5. Turn on the Enable button

Enabling users to text chat each other

  • Allow users to voice chat each other
    1. Click on the section 2 of our chat widget
    2. Click on the customization tab in section 3
    3. Click on Photos, Videos & Files accordion tab
    4. Click on Send Voice Notes
    5. Turn on the Enable button

Enabling users to voice chat each other

  • Allow users to video call each other
    1. Click on the section 2 of our chat widget
    2. Click on the customization tab in section 3
    3. Click on Photos, Videos & Files accordion tab
    4. Click on Send Photos & Videos
    5. Turn on the Enable button

Enabling users to video call each other

  • Group Chat
    1. Click on the section 2 of our chat widget
    2. Click on the customization tab in section 3
    3. Click on Groups accordion tab
    4. Turn on all the buttons there

Group Chat Customization

Add CSS

If you notice, our application is done but it is a bit off when it comes to styling. Let's make it more appealing with a bit of CSS.

  • Create a new file with the name: style.css

  • Add the following code to the file


body{
    font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;

    padding: 0;
    margin: 0;
}

/* main container */
#main_container{
    background-color: #03A9F4;
    padding: 10px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    color: white;
}

#main_container button{
    background-color: red;
    padding: 10px;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    text-transform: uppercase;
    font-weight: bold;
    letter-spacing: 1px;
}

#main_container button:hover{
    background-color: white;
    padding: 10px;
    border: 1px solid red;
    color: red;
}

/* cometchat */
#cometchat{
    margin: 10px;
    display: flex;
    justify-content: center;
}

Enter fullscreen mode Exit fullscreen mode
  • Add the following line to the head tag of the html files

<!-- css -->
    <link rel="stylesheet" href="style.css">

Enter fullscreen mode Exit fullscreen mode

Now our app looks like this:

jQuery Chat App with CSS

Log in with 2 different accounts on different browsers and try the following:

User to User chat in action
User to User chat in action

Group Chat in action
Group Chat in action

Creating Group and adding members in action
Creating Group and adding members in action

How Awesome!!!

Conclusion

I really feel like not concluding this tutorial but it is important that I let you explore the hidden treasures stored up in CometChat for developers.

We were able to see how to create an account with CometChat, how to create a chat widget and integrate it into our jQuery website. We also went ahead to customize the chat widget to our taste and as a bonus, we styled our application to be even more appealing.

I will indulge you to take out more time and re-visit the chat widget customization. You will notice that there are so many options we didn't explore together. Please play around with them and see what you can come up with.

You can find the source code to jQuery Chat App we just built here

If you're considering expanding this chat app, here are a few resources to consider:

Top comments (0)