0

I want to append an li to a ul when a user disconects. (user has disconnected).

I don't know what's wrong with my code but I can't get the event to fire.

Here's my server.js

    socket.on('disconnect', function(data) {
    users.splice(users.indexOf(socket), 1);
    console.log('User Disconnected: %s users connected.', users.length);
    io.sockets.emit('counter', {users : users.length});
 })

Which console.logs and counts the users without a problem. But when I try using the same call on the client.js:

        socket.on('disconnect', function () {
        $('#output').append('<li class="collection-item red-text">User has 
        disconnected</li>');
    })

Nothing gets appended to the UL. I'm probably missing something but can't see what. Any help appreciated!

  • What do you do to disconnect the socket in order to trigger the `disconnect` event on the client? If the socket is just disconnecting when the page closes, then the page won't be able to display anything at that point. – jfriend00 Jul 13 '18 at 02:56
  • It’s just when the page closes the disconnect event should be fired. I want the message to be shown to all other connected users that someone left. – Josh Williams Jul 13 '18 at 10:45
  • The client side disconnect will not get to run when the page closes (the page has closed so it's not still running). But the server-side disconnect event will get to run when the page closes so you can send to the other clients from the server. – jfriend00 Jul 13 '18 at 17:31
  • How would I add the message for the other clients to see that a user has disconnected? – Josh Williams Jul 13 '18 at 18:13
  • From the server, `io.emit(msg, data)` will send to all connected clients. Not sure what else you're asking. – jfriend00 Jul 13 '18 at 18:18

0 Answers0