Home > Software design >  "typing..." notification persists when chatte deletes what we wrote
"typing..." notification persists when chatte deletes what we wrote

Time:10-11

I'm trying to make a chat project, but when we write something in the chat and then delete it instead of sending it, the "typing..." message still persists on the other side. I don't understand exactly where is the error in my code?

Node.JS;

const express = require('express');
const socket = require('socket.io');

const app = express();
const server = app.listen(3000)

app.use(express.static('public'))

const io = socket(server);

io.on('connection', (socket) => {
    console.log(socket.id)

    socket.on('chat', data => {
        io.sockets.emit('chat', data)
    })
    socket.on('typing', data => {
        socket.broadcast.emit('typing', data)
    })
})

JavaScript;

const socket = io.connect('http://localhost:3000');

const sender = document.getElementById('sender');
const message = document.getElementById('message');
const submitBtn = document.getElementById('submitBtn');
const output = document.getElementById('output');
const feedback = document.getElementById('feedback');

submitBtn.addEventListener('click', () => {
    if (sender.value != '' && message.value != '') {
        socket.emit('chat', {
            message: message.value,
            sender: sender.value,
        });
        sender.disabled = true;
    }
})

socket.on('chat', data => {
    feedback.innerHTML = ''
    output.innerHTML  = '<p><strong>'   data.sender   ' : </strong>'   data.message   '</p>'
    message.value = '';
})

message.addEventListener('keypress', () => {
    if (message.value.trim() != false) {
        socket.emit('typing', sender.value)
    }
    else {
        feedback.innerHTML = ''
    }
})

socket.on('typing', data => {
    feedback.innerHTML = '<p>'   data   ' typing...</p>';
})

CodePudding user response:

socket.on('typing', data => {
    feedback.innerHTML = '<p>'   data   ' typing...</p>';
    // clear feedback after one second of inactivity
    setTimeout(() => {
        feedback.innerHTML = ''
    }, 1000);
})
  • Related