Creating the Front-End
In this module, you will design and build the front-end of your real-time chat application. This involves creating the user interface with HTML and CSS and connecting it to the server using JavaScript. By the end of this module, you will have a functional chat interface that allows users to communicate in real-time.
Setting Up the HTML Structure
Step 1: Creating the HTML File
Start by opening the index.html
file located in the public
folder. This file will serve as the main structure of your chat application.
-
Basic HTML Structure: Set up a basic HTML document structure:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Chat Application</title> </head> <body> <div id="chat-container"> <div id="messages"></div> <input id="message-input" placeholder="Type your message here..." /> <button id="send-button">Send</button> </div> <script src="/socket.io/socket.io.js"></script> <script src="script.js"></script> </body> </html>
Step 2: Adding a Chat Container
The #chat-container
div will hold the messages and input field. Make sure the #messages
div will display the chat history, while the input field will allow users to type their messages.
Styling the Chat Application
Step 1: Opening the CSS File
Next, open the style.css
file in the public
folder. This file will define the look and feel of your chat application.
Step 2: Adding Basic Styles
Add styles to make your chat interface user-friendly. Start with some basic CSS:
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
#chat-container {
width: 400px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
background: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
#messages {
height: 300px;
overflow-y: scroll;
border: 1px solid #ccc;
margin-bottom: 10px;
padding: 10px;
background-color: #f9f9f9;
}
#message-input {
width: 70%;
padding: 10px;
}
#send-button {
width: 25%;
padding: 10px;
}
Step 3: Improving the User Experience
You may want to enhance user experience further by adding styles for messages. For example, you could differentiate between user messages and system notifications.
.message {
margin: 5px 0;
}
.user-message {
color: blue;
font-weight: bold;
}
.system-message {
color: gray;
font-style: italic;
}
Writing the Client-Side JavaScript
The client-side JavaScript will manage interactions between users and the server. This file will handle sending messages, receiving messages, and updating the UI accordingly.
Step 1: Creating the JavaScript File
Open the script.js
file in the public
folder. This file will contain all the client-side logic for your chat application.
Step 2: Establishing Socket Connection
At the beginning of script.js
, establish a connection to the Socket.io server:
const socket = io();
Step 3: Handling User Input
You need to capture user input from the message input field and emit it to the server. Add an event listener to the send button:
const sendButton = document.getElementById('send-button');
const messageInput = document.getElementById('message-input');
sendButton.addEventListener('click', () => {
const msg = messageInput.value.trim();
if (msg) {
socket.emit('chat message', msg);
messageInput.value = ''; // Clear input field after sending
}
});
Step 4: Receiving Messages
Listen for incoming messages from the server. When a message is received, update the chat display:
const messagesContainer = document.getElementById('messages');
socket.on('chat message', (msg) => {
const messageElement = document.createElement('div');
messageElement.classList.add('message');
messageElement.textContent = msg;
messagesContainer.appendChild(messageElement);
// Scroll to the bottom of the messages container
messagesContainer.scrollTop = messagesContainer.scrollHeight;
});
Step 5: Setting User Names
Prompt the user for their name when the application loads. This name will be sent to the server to be used in messages.
const userName = prompt('What is your name?');
socket.emit('set name', userName);
Enhancing the User Interface
To improve the overall look and usability of the chat application, consider adding additional features.
Step 1: Displaying User Names
You can modify the message display logic to include user names. Update the message handling code to include the user's name in the displayed message:
socket.on('chat message', (msg) => {
const messageElement = document.createElement('div');
messageElement.classList.add('message');
const parts = msg.split(': '); // Assuming format "Name: message"
const user = parts[0];
const messageText = parts.slice(1).join(': ');
messageElement.innerHTML = `<span class="user-message">${user}:</span> ${messageText}`;
messagesContainer.appendChild(messageElement);
});
Step 2: Adding Notification for New Users
You might want to notify users when someone joins or leaves the chat. For this, modify the server code to emit a notification when users connect or disconnect. Then, listen for this notification in your client-side code.
-
Modify Server Code: In the
connection
event, add a line to emit a system message:socket.broadcast.emit('chat message', `${users[socket.id]} has joined the chat`);
And in the
disconnect
event:socket.broadcast.emit('chat message', `${users[socket.id]} has left the chat`);
-
Handle System Messages: Update your client-side code to format system messages differently. You can use a conditional statement to check if the message contains a specific format (e.g., "has joined" or "has left").
socket.on('chat message', (msg) => {
const messageElement = document.createElement('div');
messageElement.classList.add('message');
if (msg.includes('has joined') || msg.includes('has left')) {
messageElement.classList.add('system-message');
}
messageElement.textContent = msg;
messagesContainer.appendChild(messageElement);
});
Step 3: Mobile Responsiveness
Consider making your chat interface responsive for mobile users. Adjust your CSS with media queries:
@media (max-width: 600px) {
#chat-container {
width: 90%;
}
#message-input {
width: 70%;
}
#send-button {
width: 25%;
}
}
Testing the Front-End
After implementing the front-end components, it's crucial to test the application to ensure everything is functioning correctly.
Step 1: Running the Application
Make sure your server is running, and open multiple browser tabs to simulate different users.
Step 2: Sending and Receiving Messages
Try sending messages and check if they appear in all connected clients. Ensure that user names are displayed correctly, and test the notifications for joining and leaving.
Step 3: Check for Responsiveness
Resize your browser window to see how the chat application adjusts on smaller screens. Ensure all elements remain accessible and usable.
Conclusion
In this module, you created the front-end for your real-time chat application. You designed the HTML structure, styled the application with CSS, and wrote client-side JavaScript to handle interactions. With a fully functional front-end in place, you are now equipped to enhance features further or explore more advanced concepts in the next modules. This foundation sets the stage for a rich user experience in your chat application.