R
R
rinatoptimus2018-01-13 22:51:19
JavaScript
rinatoptimus, 2018-01-13 22:51:19

How to add message send time in Socket.io?

There is a simple chat prototype, how to make it so that the time of its sending is displayed next to the message? Used by MongoDB, Socket.io
HTML:

<form id="chat">
  <input type="text" id="username" class="form-control" placeholder="Введите имя" required>
  <br>
  <div class="card">
     <div id="messages" ></div>
  </div>
  <br>
  <textarea 
    id="textarea"
    class="form-control"
    name="message"
    placeholder="Введите сообщение" 
    required></textarea>
    <br>
    <input id="sumbmit" class="btn btn-primary" type="submit" value="Отправить">
</form>

(function(){
  var element = function(id){
    return document.getElementById(id);
  }

  var status = element('status');
  var messages = element('messages');
  var textarea = element('textarea');
  var username = element('username');

  // статус по умолчанию
  var statusDefault = status.textContent;

  var setStatus = function(s){

    status.textContent = s;

    if(s !== statusDefault){
      var delay = setTimeout(function(){
        setStatus(statusDefault);
      }, 4000);
    }
  }

  // соединение с сокетом
  var socket = io.connect('http://127.0.0.1:4000');

  // проверка соединения
  if(socket !== undefined){
    console.log('Соединение установлено');

    socket.on('output', function(data){
      if(data.length){
        for(var x = 0; x < data.length; x++){
          var message = document.createElement('div');
          message.setAttribute('class', 'chat-message');

          if(x % 2 == 0) {
            message.classList.add('bg-odd');
          }

          message.textContent = data[x].name + ": " + data[x].message;
          messages.appendChild(message);
          messages.insertBefore(message, messages.firstChild);
        }
      }
    });

    // получение статуса с сервера
    socket.on('status', function(data){
      setStatus((typeof data === 'object') ? data.message : data);

      if(data.clear){
        textarea.value = '';
      }
    });

    // прослушиваем поле textarea
    textarea.addEventListener('keydown', function(event){
      if(event.which === 13 && event.shiftKey == false){
        socket.emit('input', {
          name: username.value,
          message: textarea.value
        });
        event.preventDefault();
      }
    });

    var sumbmit = document.getElementById('sumbmit');
    sumbmit.addEventListener('click', function(event){
      socket.emit('input', {
        name: username.value,
        message: textarea.value
      });
      event.preventDefault();


      var currentdate = new Date(); 
      function formatDate(date) {
        var monthNames = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];

        var day = date.getDate();
        var monthIndex = date.getMonth();
        var year = date.getFullYear();

        var timestamp =  currentdate.getHours() + ':' + currentdate.getMinutes() + ' ' + day + '.' + monthNames[monthIndex] + '.' + year;
        return timestamp;
      }

    });

  }

})();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SagePtr, 2018-01-14
@SagePtr

In the event on the server side, where the message is received and added to the database, add to this message, in addition to the user and message fields, also the time field, in which to write the current time (for example, via Date.now())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question