Hey.

I have a WebSoket chat, and I need to complete this task. When sending my message to the server, the div class must be set to mymessage, otherwise message. How can I accomplish this task on JS? Thank you in advance.

  • @Leva Chernenko, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky

2 answers 2

Each message has its own id. In the place where the list of messages is generated, each div element must be assigned id = id_message.
Then, by sending a message, a new message is generated with a new id.
This id is passed to the JavaScript function, which will be the following code for changing the class:

$('#id_message').attr('class', 'mymessage'); 

And in idel instead of attr it is better to use .removeClass and .addClass .

P.S. I would send a message to implement asynchronous-ajax, which in return will return to us json, which will contain the message id. And after that you change the class to mymessage.

  • The socket server does not send any id messages, bare text. - Lyova Chernenko
  • Give the url on which this chat is installed. And I’ll look at the code and then I can answer that thread to you - MarinaVoin

I do not fully understand the data sent and received?

 var ws = new WebSocket('ws://site'); //при получении ws.onmessage = function(e) { $('.class_div').html(e.data); }; //при отправки WSSend = function(msg,ws) { ws.send(msg); $('.class_div').html(msg); } WSSend('тра-ля-ля',ws);