Simplest Method To Create A Group Chat Web App 2020




Course Materials:

1. Browsers. One browser is okay if you just care to see the app working.

2. Code Editor. Code editor can be anything to type with like MS Word, WordPad, or even Notepad. However, it is better to get professional editors like Atom, VS Code, etc. They make debugging a lot easier.

3. A web template. Read on for more information.

4. A firebase account and a firebase web app. Read on for more information.

5. Optional. A Web server app. Read on for more information.


HTML Introduction (you can skip this if you are familiar with html already)

So, for the sake of those who are new to websites or web applications, think of websites as a set of documents. Each document is related to the other by purpose. For instance, a business plan would usually contain a set of documents where one of them, usually the front document, would have words that introduces the business in few words, probably telling the problem that the business tends to solve and a brief overview of how to solve it, as most investors may not have much time to read more than this front page. There would be another page that talks about the business, and another page that shows the feasibility studies, and so on. The most important and interesting thing about these set of documents is that they are linked to each other usually by reference. For instance, the page that talks about the solution process may include a "see page 45 for more information" reference. More so, each document will have its own introduction, body and conclusion. The introduction could have the title, headings, etc. While the body would have sections for subheadings, paragraphs, etc., and the conclusion would contain the footer, etc. 

So also, you create different pages known as webpages, in website development, and link them together through references known as hyperlinks. This hyperlinks may be clicked to go to the webpage that the link refers to. Each webpage would have the header or simply head, the title, the body, paragraphs, sections, footers, etc., each relating to a particular subject corresponding to the website. The result of these becomes your eventual website.
Like I said previously, web documents contains elements as header, headings, titles, body, paragraphs, etc. Yes! Just like your MS Word document. However, it is a bit easier to create MS Word documents elements than it is to create web documents elements. 
For instance, to get a paragraph element in MS Word document, you hit the enter key, but in a webpage, you define a paragraph element by enclosing your paragraph in what we call a paragraph tag, like:

<p> this is my first paragraph </p>
<p> this is my second paragraph </p>

So anytime you want a paragraph element, never hit the enter key, but rather enclose your paragraph text in those <p>...</p> tags.

Tags does not end with paragraphs. In fact, almost everything you would do while writing your web document from scratch would require defining a tag. For instance, to define a title element, you write your title inbetween the title's open and close tags, like:

<title> My title </title>

For body element definition, it is like:

<body> my body </body>

Also, if you need to add image, there is an <img> tag for that, etc.

Always take note of the difference between open and close tags. They do not always look the same.

And extra-finally,  like seriously, there are VIP tags that you must learn to use. Join me with standing ovation while I introduce to you the mighty 

<div></div> and 
<span></span> tags.

The div and span tags are usually used to format or arrange your html document through your elements' class attributes. As you will see shortly that elements usually have attributes or properties, where you save data associated with them, to be used later for different purposes. Attributes usually come in attribute-name and attribute-value pairs or simply, name-value pairs.
Now, you are ready to create a web document. Note, however, that, a web document is also known as an html document.

You can read more about html documents online.

Back to business...

In the case of our web app, we would not have many webpages as our app is a Single-Page App (SPA), unlike the multipage web app. More so, we would not create our documents from scratch, as you would prefer to use, if found, an already created web template which you would modify to suit your purpose, in order to save time. There are probably many web templates for our purpose, many of which are probably plug and play. Why then would we create another web document from scratch?

The first thing we would do is download our web template, i.e. the web document we will use. Please, note that this web template is developed courtesy of Adnan Tech and can be downloaded through here

Now, if you have a glance into this folder,  you would see the following files and folders.
 

If you connect your firebase database to this template, it works perfectly. You can check how to connect your firebase realtime database below.

This web document is plug and play, but combines some things like jQuery syntaxes and PHP capabilities that we would not use in this project, as I wish to keep things extremely simple. 
Basically, a web developer must learn HTML, CSS and Javascript, and these days, you may not need to learn more, except if you are interested in code optimization offered by the many, new frameworks. 
However, since our goal is to keep things extremely basic, rather than optimizing our code, we would use only the three web languages that are mostly necessary. Then, you can extend this knowledge to other frameworks if you so wish.

1. Firstly, create your own new folder. This will be your main or root folder. You will see the reason why our files must be coordinated shortly. Till then, you can name your folder anything. I will call mine chat-example.

2. Copy and paste the index.php file from your web template into your own root folder. Rename your index.php file as index.html. (To do this, right-click on the file and click rename from the context menu. Make sure you can view file extension). What you have now is, no less, your html document. If you open this file (by double clicking), you will not be happy you did because, it looks so dry, as there is no colour, nice font styles, etc. At least, I was not! We would however add that in a giffy. 

Note, HTML only makes it possible to add elements with default looks which are always dull or even dumb.

To tidy things up, you need to arrange and format the elements your documents are made of. Both arrangement and formatting are called styling in web design. There are different ways to style, but they all use the same language called CSS. You can find out more information on CSS.

So, let us add the styling to our document...

We will create our styling using one of the 3 methods. That is creating an external styling file as it is a good practice to separate your html document from your styling. We will however keep everything simple.

3. Now, open the css folder in your web template, and copy the style.css file into your root folder. You can leave its name, but i renamed mine as index.css for uniformity.
If you open the html file now or even the css file, you would still not be happy you did. You would see why shortly.



 

4. Finally, open the js folder in your web template, and copy the index.js file into your root folder. 

At the end, you should have something like this:
 

You may delete your template now if you so wish.

Note that before you test your external styling, you must tell your browsers that you have added an external styling file. 

Now right-click your index.html file, and open it with your editor, and take a peep. Before you start getting scared of the entire structure, delete everything in that file. Yes! Everthing!! We will re-write it from scratch.

Copy and paste the following:

<!DOCTYPE html>  
<html>
<head>
<title>Page Title</title>
</head>
<body>


</body>
</html>

You should take your time to examine this code, in order to identify the tags and which portion of the document they represent or render. However, for those who are not familiar with these codes, the first line is a rule, use it for all your html pages to define your document type as html. It could have been a different document type, I guess.

After that, you can start constructing the structure of your document. Your document would have a grandest-parent tag as <html>, that would habour all your other tags. This is the workable structure and also for other situations you will learn about shortly.
Then define the header using the head tag. Inside this tag would be the title tag to define your title. Other information may be included in the header, such as author, address, etc. We however do not need all those here.

Finally, we would include the body tag. It is in here that you will include every element you want to show in your webpage when your users open it. The title information would be shown in the browser tab too. You can learn more about the kinds of tags that would be in the body tags. They are countless, I guess!

In the title, however, put anything you want. In my case, I would use the name of my folder. 
Please note, that the heading tag, used for sub-headings, is entirely different from the head tag, used for the header. heading tags have levels based on how big and bold you want your subtopics to be. Here we would use heading tag, level 2. You can try with different levels between and including one and six. For example:

<h2> Firebase <h2>

you can put anything you want as the heading inside the tag.
Still inside the body tag, however, include the following elements that we want to show on our webpage, like this: 

<body>
<div class="chat">
  <div class="chat-title">
    <h1>Chat Room</h1>
    <h2>Firebase</h2>
    <figure class="avatar">
      <img src="https://p7.hiclipart.com/preview/349/273/275/livechat-online-chat-computer-icons-chat-room-web-chat-others.jpg" /></figure>
  </div>
  <div class="messages">
    <div class="messages-content"></div>
  </div>
  <div class="message-box">
    <textarea type="text" class="message-input" id="message" placeholder="Type message..."></textarea>
    <button type="submit" class="message-submit">Send</button>
  </div>

</div>
<div class="bg"></div>
</body>

There are some tags here that we have not introduced. Those are the figure, text-area and the button tags. Figure tags are used to hold figures such as illustrations, diagrams, photos, code listings, etc. The textarea is one of the many tags used in getting inputs from the user. In this case, it would be the a text that represents the message when chatting. The button tag is used to define the send button, which is clicked to trigger the send message event. Image tags are obviously used to hold a photo. You specify the location or URL of the photo using the 'src' attribute for source.

They all have classes to change their looks. You will delve into styling shortly. 

To attach the external CSS styling file, include the following atop your index.html document file , within your head tags like this:

<head>
<title>Chat Example</title>
<link rel="stylesheet" href="index.css">
</head>

The added line only means that we have linked an external styling file, and that it is located in the root folder. You can now open your webpage.


 

happy now?! Weldone!!

Note, however, that if you have not structured your files well by having everything in a root folder, it would be harder to locate them as your browser starts searching from the directory where your html document is harboured. Locating external file is done in two ways. We have the absolute and the relative methods. You may read more about them.

Now, open your index.css file so you can get acquainted with CSS syntaxes.

If you look closely, you will notice that we have nothing other than identifying our elements by their class attributes, and then changing their properties like size, color, background, outline, border, border-radius, etc. There are tonnes of, perhaps endless, style properties. The more properties you know and can use, the better the quality of your webpage. 

We also added some transitions. Transition capabilities, with transformations and animations, can turn things around if you learn to use them well. You should also not that, apart from identifying elements by classes, there are many other ways of identifying an element. Identifying elements is key to CSS! You can learn more about CSS in order to secure for yourself an amazing web design future.

Keep in mind that styling is basically identifying an element by its class, and changing its style attributes. A very good practice however, is to add comments to your codes so as to make it more readable. Another way to enhance the readability of your code is to structure it in a special way. You should learn about adding annotations and structuring your code if you hope to meet acceptable standards, and also collaborate with professional programmers. One way that CSS enforces code groupings is by enclosing related codes inbetween curly braces as you must have discovered in this code.

Unnecessarily, but intentionally, we would meddle with this file as follows.

Scroll down and locate the comment:

/*--------------------
Custom Scrollbar
--------------------*/

Delete everything under and including it, as we would use one simple command to perform the same scrolling function. You can download the eventual project in the link supplied below.

Two more steps to go, however!

If we were creating a static web app, I would have congratulated you or given you a certificate of completion. But, since we still need to add some magical capabilities to your web app, hence, we will have to continue...

Most times, these days, what happens in web apps when users interact with them are different from what you see when you initially open them. For instance, when chatting, you will need to add new text that were not there initially. You may as well need to delete messages, etc. All these appearings and disappearings, transformations, animations, transitions, and other something-tions must be added on run-time. You must document all these expectations before designing your pages so that implementing them would be easy.
To add these magic, this is where Javascript comes in handy.

But just before we create our Javascript file, we will need to take care of the means of storing our messages so we can retrieve them later. We could do that on the client machine, but if the client machine spoils or if the client, that is, your user changes his machine, he or she may need to forget about his messages. Apart from this, we need to demonstrate back-end development as you usually cannot do without them these days. For this, we will use a google solution known as firebase.

To use firebase, open firebase.com from your browser. You will see a page like that below. Click on get started.



 Then on the add project panel from the window that opens


Follow the instructions to create a project for the database we will be using. Name your web app project. Mine has always been the same.



 You can skip the analytics options to save time and then continue. We would not need the analytics option. Besides, you can add them later if you want.
 



 You have your project. Click on the name of your project to access your database. 


This firebase project gives you access to many features like authentication, real-time database (we would use this), cloud storage, hosting, machine learning capabilities. You should check them later on.




Now that your project is ready, we should should add and connect firebase to our app. To do this, we need to copy and paste some special codes from firebase into our created web app. 
Do the following to get the connection codes from firebase:

1. Log in to your firebase account with your browser, if you have not already.
2. Click the gear icon near the project overview menu and click on project settings from the drop right that appears.





On load, scroll down to see your apps panel, click on the button </> signifying that you want to connect firebase to a web app as opposed to an Android or IOS app.


You would be shown the information you need. You can copy and save them somewhere, or go back to the project settings to get the information as many times as you need.


So, we can continue with our js file. We will also use Javascript to interact with the database, thereby eliminating the need for other used-to-be-inevitable programming languages and frameworks.

Open your index.js file from within your root folder.

What you have there are jQuery syntaxes. jQuery is a modified or optimized version of javaScript. There has been a great shift to optimized JavaScript versions such as JQuery, React, etc. However, to keep everything simple, we will convert these code to pure JavaScript. It is easier to understand JavaScript.

Note also, that when I asked you to take a peep into your index.html file the other time, there were some CSS and JavaScript codes in it. It was easier to write all these extra codes and more in one PHP file. However, because, we intend to keep things simple and separated, we removed all those extra-extras and amalgamations.

 Here, you will program your browser to dance to your tunes, using the Javascript language. Programming is getting easier everyday through already-created programs or frameworks that you can just reuse in your works. In fact, these frameworks are the inspiration behind this tutorial. It would have been worse having to write additional PHP, SQL and AJAX codes just to finish this project. So, you should give programming a try.

Delete everything in the index.js file and copy and paste or type the following in your index.js file:

  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "sooJosr_ruUHjirl6nlsdiurkfIJijuBiilsr_A",
    authDomain: "chat-Example-r4a35.firebaseapp.com",
    databaseURL: "https://chat-Example-r4a35.firebaseio.com",
    projectId: "chat-Example-r4a35",
    storageBucket: "chat-Example-r4a35.appspot.com",
    messagingSenderId: "234544657566",
    appId: "1:AA8a6ILLh664:web:airgu6684oddsdr",
    measurementId: "G-AA8a6ILLh664"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

  var myName = "";

  window.onload = function() {

    var  myName = prompt("Enter your name");

    reloadMessage(myName);

    document.getElementById('send').addEventListener('click', function() {
      sendMessage(event);
    });
  }


function reloadMessage(mN) {
    myName = mN;

    firebase.database().ref("messages").on("child_added", function (snapshot) {
      if (snapshot.val().sender == myName) {
         var div = document.createElement('div');
         div.setAttribute('class', 'message message-personal');

         var fig = document.createElement('figure')
         fig.setAttribute('class', 'avatar');
         div.appendChild(fig);
         var img = document.createElement('img');
         img.setAttribute('src', "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQpdX6tPX96Zk00S47LcCYAdoFK8INeCElPeJrVDrh8phAGqUZP_g");
         fig.appendChild(img);

         var div2 = document.createElement('div');
         div2.setAttribute('id', "message-" + snapshot.key);

         div2.innerHTML = snapshot.val().message;
         div.appendChild(div2);

         var mcb = document.getElementById("mc");         //.setAttribute('class', 'new');
         mcb.appendChild(div);

         div.scrollIntoView();

         var ta = document.getElementsByClassName("message-input");
         ta[0].value = null;

       } else {

         var div = document.createElement('div');
         div.setAttribute('class', 'message message-other');

         var fig = document.createElement('figure');
         fig.setAttribute('class', 'avatar');
         div.appendChild(fig);

         var img = document.createElement('img');
         img.setAttribute('src', "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQpdX6tPX96Zk00S47LcCYAdoFK8INeCElPeJrVDrh8phAGqUZP_g");
         fig.appendChild(img);

         var div2 = document.createElement('div');
         div2.setAttribute('id', "message-" + snapshot.key);

         div2.innerHTML = snapshot.val().sender + ':  ' + snapshot.val().message;
         div.appendChild(div2);

         var mcb = document.getElementById("mc");//[0].setAttribute('class', 'new');
         mcb.appendChild(div);

         div.scrollIntoView();

         var ta = document.getElementsByClassName("message-input");
         ta[0].value = null;

       };
    });
  }


  function sendMessage(event) {
    var message = document.getElementById("message").value;
    firebase.database().ref("messages").push().set({
      "message": message,
      "sender": myName
    });
    event.stopPropagation();
  }

We grouped our programs according to their functions. We wrote a program that will perform the send message function. Also, we wrote programs that will load messages from our database, etc. To group programs by function, we used the function command and enclose our block of codes within curly braces.

More so, we created the new html elements with JavaScript using createElement( ) command. Also, we added new attributes or properties using setAttribute( ) command, whereas appendChild( ) command or function was used to add the created elements to their parent element so they can be shown. You can get already created elements by their attributes as usual. Built-in attributes can be an id, or a class, etc, whereas custom attribute would be data-abc. Abc can be anything you choose which you must have defined before referring to them. You can define attributes either directly in your HTML document, CSS document or from your JavaScript program.

Note that the first 10 lines in the JavaScript files above must be replaced with your connection code from firebase project settings, configuration information, that you got earlier.

To store values in programming, variables, rather than constants, are used. var myName = prompt('Enter your name'); is used to create a variable to store the name of the user. We used the prompt JavaScript built-in function to prompt the user to input his or her name.

The structure of our JavaScript program were declared in the following:

1. The window.onload = function () { };

Closely looking at this segment, you will notice that it adds an event to be triggered when your document has been completely loaded by your browser. The codes within the braces will be triggered upon load. These function triggers the reloadMessages( ) function which loads messages from our database. Note that we defined reloadMessages( ) function below the onload function. You must have defined any object you plan to refer to. 

We sent the the myName data to the reloadMessages( ) function which takes the variable in order to decide who has sent which message. If the message is owned or sent by the system user, html elements are created, holding the message and sender, which are eventually appended to the left of the screen. If not, html elements are created, holding the message and sender, and appended to the right of the screen. 

Please note that reloadMessage is referred to or called each time there is a new message in the database. We added this possibility using:

firebase.database().ref("messages").on("child_added", function (snapshot) { });

It says, perform the following activities (inside the curly braces)  when a child is added (or on child added)  under the message parent object. Check the following structure:

 

To view the structure of your database, click on database option on the right. Then scroll down to choose Realtime Database, and click Create database:

 

You may have to go to console and then select your project to see project setting






To understand database structure, find more information on json format.

2. We also added another on-click event using a different method (by choice) to the send button as follows.
 
document.getElementById('send').addEventListener('click', function() {
    sendMessage(event);
});

Majorly, interactions to your programs, by your users or clients, should trigger an event that performs a particular function. In this case the function triggered is the sendMessage function which collects the value of your text box, that is, the message typed by your user and then sends it to your database


Two more commands to go:

First, is the 

div.scrollIntoView( ); to perform the auto scrolling. 

Scrolling here ensures that your last message (parented by the div element) is always on view or scrolled into view.

And finally-finally, 

event.stopPropagation( ) is a built-in function to prevent re-triggering of the same event.

Remember to save all your file.

The completed web document may be found hereor here.

You can double-click your html document now to test your app. You may, optionally, convert your system into a local server by installing server app like wamp, xampp, etc. so you can host your web app directly on your computer. You could read more about serving websites locally.

With this tutorial, you have learnt to create a scalable group chatting web app suitable for any organization. You can sell this app to SMEs to enhance team collaboration, or teach it to earn money.

I am doing a course on real-time, one-to-one webchat app with video and audio call capabilities like Facebook and WhatsApp, for just $ 5 (N 2000 for Nigerians). Follow me on blogger, youtube, instagram, facebook and twitter for more free earning money tips.

Well, certificate of completion is only for static webpages. Winks! However, since this project is dynamic, I am sure that congratulating you would be enough. Drop your comments and challenges below. 

Enjoy!



Ibukun Olofin is a senior software/systems developer
@Cardis since 2009, whose heart melts whenever he 
sees a sincere smile or laughter.

Hire Me!
+2348101691795
giftedcardis@outlook.com
bit.ly/cardisdevs








Cardis is proudly powered by:

  

...The World Needs You...

Comments

Popular posts from this blog

Solve Complex Maths Like ODE with Laplace, Maclaurin's Series Expansion, Fourier Series Expansion and the Heat Equation (PDE) with Matlab. [Cardis!]

Create a filemaker app that integrates google map api for drawing regions and testing coordinates.