My latest project involves creating a chat room using NodeJS and socket.io which allows multiple users to connect with unique usernames. Everything is running smoothly, except for one minor issue.
I want the messages sent by me to appear in a different color compared to messages sent by other users. I attempted to use even odd logic in CSS, but it didn't work as expected when I sent multiple messages simultaneously.
Below is the structure of my Index.html file:
<div id="wrapper">
<div id="usernameWrap">
<p id="usernameError"></p>
<form id="setUsername">
<input class="message" id="username" placeholder="Enter your Username"/>
<input class="button" type="submit" value="SUBMIT"/>
</form>
</div>
<div id="chatWrapper">
<ul id="chat"></ul>
<form id="send-message">
<input class="message" type="text" id="message" placeholder="Type a message" autocomplete="off" />
<input class="button" type="submit" value="SEND"/>
</form>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket =io.connect();
var $usernameForm = $('#setUsername');
var $usernameError = $('#usernameError');
var $username = $('#username');
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
/* setting username */
$usernameForm.submit(function(e){
e.preventDefault();
socket.emit('new user',$username.val(),function(data){
if(data){
$('#usernameWrap').hide();
$('#chatWrapper').show();
} else{
$usernameError.html('Username is already Taken!');
}
});
$username.val('');
});
/* sending and receiving messages */
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message',$messageBox.val());
$messageBox.val('');
});
socket.on('new message',function(data){
$chat.append('<li><b>' + data.username + ': </b>' + data.message + "<br/></li>");
});
});
</script>
Below is the content of my App.js file:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
usernames=[];
app.use('/css', express.static(__dirname + '/css'));
server.listen(8081);
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html')
});
io.sockets.on('connection',function(socket){
socket.on('new user',function(data,callback){
if(usernames.indexOf(data) != -1){
callback(false);
} else{
callback(true);
socket.username = data;
usernames.push(socket.username);
io.sockets.emit('usernames',usernames);
}
});
socket.on('send message',function(data){
io.sockets.emit('new message',{message:data,username:socket.username});
});
socket.on('disconnect',function(data){
if(!socket.username) return;
usernames.splice(usernames.indexOf(socket.username),1);
});
});
Thank you for taking the time to review my project.