Search code examples
javascriptnode.jsexpresssocket.iodrag-and-drop

Drag and drop With Socket io


I'm creating a multiplayer card game with node, express and socket io. I'm having issues being able to pass drag and drop actions made by one player to the screen of a second player connected.

Basically I use this function to handle the drop event on client side. I get the id of the card moved and then append it to the dropzone where its moved

function handleBoxDrop(e) {
    const id = e.dataTransfer.getData('text');
    let dropzone = e.target;
    socket.emit('drop', id);

    socket.on('drop', (id) => {
      let temp = document.getElementById(id);
      dropzone.appendChild(temp);
    });

    e.dataTransfer.clearData();
  }

and on server side I used this:

o.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('drop', (id) => {
    io.emit('drop', id);
  });
});

But when I move a card, The card doesn't move on the other browser or moves to the wrong place. I don't know what I'm doing wrong, please help. Thanks:)


Solution

  • you need to move the socket.on function to outside of the handle drop function

    function handleBoxDrop(e) {
       '''your code'''
    }
    
    socket.on('drop', e => {
       '''append to dropzone'''
    })
    

    The socket.on method creates a listener and only needs to be created once. You can call it right after you instantiate the socket object.

    const socket = websocket()
    socket.on('drop', e => {})