Add “typing…” in your Chat Application using Socket.io
Hi all, I believe you’ve already built a fully functional chat application and are here to add that extra layer of UI experience for your users by notifying them whenever a person is typing.
The way we will go about it is by using socket.io library to establish real-time, bi-directional communication between web clients and servers. In simple terms, a channel that will communicate real-time changes done on client side to the server and vice versa.
First things first, you need to install socket.io library along with express from node package manager. I hope you have node.js installed in your local machine. Run the following command on your terminal after going to the location of project directory.
npm install --save socket.io express
Now you’ve installed socket.io and added it to package.json file.
Client Side
Setup socket and jquery on client side so that script section looks like this.
A typing event will be triggered when the user is typing in message box. You have to capture this event and to achieve this we will use jquery library function keypress(). Declare the following variables in your javascript file associated to your html file.
var socket = io();
var typing=false;
var timeout=undefined;
var user;
Now in document.ready() method we will try to emit a socket event ‘typing’. Here message-box is the id of the input element being used to send the message. You can change it according to your needs.
Server Side
In server.js file we will first setup socket.io and try to capture the ‘typing’ event emitted from the client side.
Back on Client Side
Here we will capture the ‘display’ event and fill the div element of typing class with text “<username> is typing…”
socket.on('display', (data)=>{
if(data.typing==true)
$('.typing').text(`${data.user} is typing...`)
else
$('.typing').text("")
})
Here’s the git repository of the entire chat application. You can go have a look as to how this fits into the whole picture. I hope I was able to explain this simple application of socket.io to achieve a small yet useful functionality. Sockets are powerful tool to establish real-time bidirectional communication between server and client, if used judicially one can achieve a lot more with it.
Cheers, until next time!