How to Create a Simple Chat Room with JavaScript

The popularity of chat rooms has been an ongoing topic since its peak in the early '90s. While much more sophisticated communication systems carry more weight today, it's still important to understand the basics.

What You'll Learn from this Article

This article explains the steps needed to create a simple chat room using JavaScript and your choice of server-side technology, between either PHP or Node.js. The client-side portion, which we'll be discussing in this article, will work with both server-side solutions.

What Are WebSockets?

A WebSocket is a computer communications protocol, providing multiple real-time bi-directional communication channels over a single TCP connection.

With standard HTTP and HTTPS connections, a server request is required to respond. The user initiates a page request to a URL, and that data is then returned to the user and displayed in a web browser.

With WebSockets, the idea of a request is different in that you can pass data to and from a server and your users without initiating a full-page request.

A few practical examples of WebSocket uses include:

  • Real-time applications
  • Chat rooms or apps
  • Notification handling
  • Online multiplayer games

The JavaScript Chat Room Code

In this case, we'll be creating a very simple chat room to illustrate the fundamentals of how WebSockets work.

First, let's get started by creating our HTML display and form:

<div id="chat">
<div id="chat-messages">

<form id="chat-form" method="post">
<input type="text" name="message" placeholder="Enter a message..." maxlength="500" autocomplete="off">
<button type="submit">Send</button>
</form>
</div>

This is a very basic form. A chat-messages container is created to hold the messages received from all users. And chat-form is created to hold an input field and submit button to send messages to the other users.

Initializing WebSockets

Now let's initialize our WebSockets:

var ws_uri = "ws://[your-domain]:9600";
var websocket = new WebSocket(ws_uri);

The ws_uri variable is the URL in which your WebSocket server is running. You'll need to make sure that you change [your-domain] to your correct domain name.

The next line initializes the WebSocket connection so you can begin sending and receiving data.

WebSocket Event Handling

There are a few note-worthy event handlers to consider when setting up your WebSocket functionality. Here are the ones we'll be using in short detail:

  • onopen: An event listener called when the WebSocket connection has opened.
  • onclose: An event listener called when the websocket connection has closed.
  • onerror: An event listener called when an error occurs with the connection.
  • onmessage: An event listener called when a message is received from the server.

Within each of these event handlers, we've added custom messages that will append to the chat-messages container, notifying anyone in the chat room of the current connection status.

// on websocket open:
websocket.onopen = function(event) {
MessageAdd('<div class="message green">You have entered the chat room.</div>');
};

// on websocket close:
websocket.onclose = function(event) {
MessageAdd('<div class="message blue">You have been disconnected.</div>');
};

// on websocket error:
websocket.onerror = function(event) {
MessageAdd('<div class="message red">Connection to chat failed.</div>');
};

We'll talk about the MessageAdd() method here in a bit.

To receive messages from the server and display them for all users in the chat room, we need to set up the onmessage event handler:

websocket.onmessage = function(event) {
var data = JSON.parse(event.data);

if (data.type == "message") {
MessageAdd('<div class="message">' + data.username + ': ' + data.message + '</div>');
}
};

This code is pretty simple. The parsed JSON data is stored to our local data variable.

A check for the data type is then done. This isn't required in all cases. Since we're passing variable type in our object and returning it from the server, I've added it here. This is to illustrate that we could send different types of data to the server and return to the user in real-time, such as a new notification, a new user entering the chat room, etc.

Submitting Form Data With WebSockets

We're setup to receive data from the server. Now we need a way to submit custom messages to other users in the chat room:

document.getElementById("chat-form").addEventListener("submit", function(event) {
event.preventDefault();

var message_element = document.getElementsByTagName("input")[0];
var message = message_element.value;

if (message.toString().length) {
var data = {
type: "message",
username: "You",
message: message
};

websocket.send(JSON.stringify(data));
message_element.value = "";
}
}, false);

This chunk of code creates an event handler for the chat-form form element we created earlier. The message is then pulled from the input field. If the message is at least one character long, a JavaScript object is created holding some data about the message, the user, and the input text. The websocket.send() method then submits a stringified version of our object to the server, and the input field value is cleared.

Display the Chat Room Messages

Finally, we'll introduce the functionality behind the MessageAdd() method:

function MessageAdd(message) {
var chat_messages = document.getElementById("chat-messages");

chat_messages.insertAdjacentHTML("beforeend", message);
chat_messages.scrollTop = chat_messages.scrollHeight;
}

Here, a message string is passed into the function, containing the input field text from our chat form. The chat-messages container is held in memory while we then append the message using JavaScript's insertAdjacentHTML() method.

At the end of our function, an automatic scroll is pushed to the chat-messages container. This ensures that, as new messages are received from the server, the container scrollbar pushes downward automatically so new messages will continue to remain in view for the user.

Conclusion

This article only touches on the very basics of what WebSockets can do. The possibilities are nearly endless as you get into developing more complex systems.

Now, you can push this chat room up to your production environment and invite your friends in for a nice chat.  But, before you do that, you'll need to setup a secure WebSocket configuration if you're using HTTPS for your website.  (There should be no if, just do it!)

You can view the full JavaScript Chat code in our GitHub repository.

For the server-side WebSocket functionality, visit our PHP WebSocket GitHub repository or our Node.js WebSocket GitHub repository