Bilal Usean Bilal Usean - 6 months ago 20
Node.js Question

click event does not work in node js

I am learning about

nodejs + express + socket.io
. I have a list of user list, list get append automatically when clients are connected. For making trial I have checked with click event with div element.

client side

<div class="userlist">
<ul>
............... ...............
</ul>
</div>

<script>
$('.userlist').click(function() {
socket.emit('private', 'test');
});

socket.on('private', function(mesg) {
$('body').append($('<li class="listm">').text(mesg));
});
</script>


server side

io.on('connection', function(socket){
socket.on('private', function(mesg)
{
console.log('private test message');
io.socket.emit('private',mesg);
});
});


But it does not work. when I click div it is not print the message in console also it will not append any text.

what did I wrong?

Answer

I can't see anything wrong with the code you've shown but here's a few things I can think of:

1. Did you remember to link the http Server instance with socket.io?

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

And then using the linked server?

server.listen(port, () => {

});

2. Did you include socket.io on the client and connected to the server after the page loaded?

<script>
// < -- is there code here that does var socket = io('{server url}';
$('.userlist').click(function(){        
  socket.emit('private','test');
});

3. If yes, did you check if the connection succeeded?

// Put this on the client and look at the console
socket.on('connect', () => {
  console.debug('Connection to server established');
});

Another thing, even though it might just be a typo in the question, on the server you need to use the socket returned from the connection callback, not io.socket:

io.on('connection', function(socket){
    socket.on('private', function(mesg)
    {  
       console.log('private test message');
       socket.emit('private',mesg); // <----- Use this (without io.)
       // Not this: io.socket.emit('private',mesg); 
    }); 
});
Comments