Thursday, 18 May 2017

Why doesn't socket.io work well with click events?

I have a very simple html code that just have

<div id="colorMe"> Change Me </div>

And I'm trying to use socket.io to color this div on all windows when clicked on any window and then when clicked again it changes its color back everywhere and so on.

But it only works the first time only and makes the color blue everywhere but never goes back to white when clicked again.

This is the server code :

io.on('connection', function(socket){

  socket.on('changeColor', function(data){
    io.emit('currentColor',data);
  });

});

And this is the javascript part at the html page :

var socket = io();

let div = document.querySelector('#colorMe');

socket.on('currentColor',(currentColor)=>{
    div.style.background = currentColor;
});


function changeColor(){
    let color = (div.style.background == 'blue')? 'white' : 'blue';
    socket.emit('changeColor', color);
}

div.addEventListener('click', changeColor);



via Youssef Mohamed

No comments:

Post a Comment