August 17, 2015 7:31 pm

How to Create Real-time Chat Application with Node.js Part 2

The client-side JavaScript First, we initialize our socket client, ask the user for a name and keep asking him until he types less than 26 characters. Then, we check if the form is submitted (there is only one form and it handles new messages) and if the message does not contain more than 100 characters we send the data to the server using the socket.emit(eventName, messageToPass) method.

Create Real-time Chat Application with Node

[wpdm_file id=147]DEMO

After that, we reset the input’s value in the form and clear any error messages. If the user’s message has more than 100 characters we do not send the data to the server but show the user an error message. The return false; in the end of the submit event listener prevents us from submitting the form in the traditional way (making a new HTTP request).

$(function() {
varsocket = io('https://infinite-brook-7325.herokuapp.com/');
varnickname = prompt("Enter your nickname:") || "Anonymous";
while (nickname.length>25) {
nickname = prompt("Enter your nickname (Max 25 characters):") || "Anonymous";
    }
    $("form").on("submit", function(evt) {
evt.preventDefault();
if ($("#msg").val().length <100) {
socket.emit("message", $("#msg").val());
            $("#msg").val("");
            $("p.error").fadeOut("slow");
        }
else {
            $("p.error").html("Message is too long").fadeIn('slow');
        }


return false;
    })

Afterwards, we emit to the server a join event giving it the nickname of the person that just joined the chat using the emit method of the socket object (socket.emit).

Next, we listen for events coming from the server named online and we respond to them by adding list items (li tags) to a list with all users that are online  (the array of users is also sent by the server along with the event name, just as we send the join event). To do that we use the client-side socket.on(“eventName”, callback);

socket.on("online", function(users) {
        $("#users-online").html("");
for (vari= 0; i<users.length; i++) {

            $("#users-online").append("<li>" +(i+ 1) + "."  + "<span class='user'>" + users[i] + "</span></li>")

        }
    });

socket.emit(‘join’, nickname);

We also listen for an incomingMessage event and respond to it by adding the message to a paragraph within our chatbox, we scroll the chatbox to that last message and use the Speech Synthesis API to read aloud the message. Notice that first we use vardecoded = $(“<div/>”).html(message).text(); to decode the message before giving it to the Speech Synthesis API. This is because we convert html characters to their respective entities when we add the messages and nicknames to the database and the DOM and we do not want the synthesizer to read aloud &quot; instead of its proper understanding of quotes (“ “).

Finally, we use    varmsg= new SpeechSynthesisUtterance(“Message to say”); to create our message and read it out aloud with window.speechSynthesis.speak(msg);

socket.on("incomingMessage", function(message) {
        $("#chatbox").append("<p>" + message + "</p>");

        $('#chatbox').animate({
scrollTop: $('#chatbox p:last-of-type').position().top + $('#chatbox').scrollTop()
        }, 1000);
vardecoded = $("<div/>").html(message).text();
varmsg= new SpeechSynthesisUtterance(decoded);
window.speechSynthesis.speak(msg);
    })
})

Speech Synthesis Browser Support

The Speech Synthesis API is supported by:

  1. Chrome 42+
  2. Safari 7.1+
  3. Opera 30+
  4. Recent iOS Safari and Chrome for Android

IE/Edge, Firefox and the Android browser does not have any support of it at the moment.

Part 1: How to Create Real-time Chat Application with Node.js Part 1

Part 3: How to Create Real-time Chat Application with Node.js Part 3

Part 4: How to Create Real-time Chat Application with Node.js Part 4

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories:

3 responses to “How to Create Real-time Chat Application with Node.js Part 2”

  1. Sud says:

    Hi Ivan Seems nice eagerly waiting for complete app. Actually Now I am learning nodejs, I want chat app to be added in my one of the web application as support chat. Means whoever visits my application he can get support from me. So I think your tutorial will help me. Please complete as soon as possible. Thank you

  2. Sud says:

    Hi Ivan Seems nice eagerly waiting for complete app. Actually Now I am learning nodejs, I want chat app to be added in my one of the web application as support chat. Means whoever visits my application he can get support from me. So I think your tutorial will help me. Please complete as soon as possible. Thank you

  3. Sud says:

    Hi Ivan Seems nice eagerly waiting for complete app. Actually Now I am learning nodejs, I want chat app to be added in my one of the web application as support chat. Means whoever visits my application he can get support from me. So I think your tutorial will help me. Please complete as soon as possible. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *