From 49104e119ab1fc236399119182e17b77fd8fc2c8 Mon Sep 17 00:00:00 2001 From: Aleksandar Matevski Date: Sun, 11 Jul 2021 00:35:48 +0200 Subject: [PATCH] Enhance typing feedback * introduce new socket event "stop-typing" * send "stop-typing" socket event when the user focuses of the message field * send "stop-typing" socket event when the user stops typing in the message field for a second --- index.js | 4 ++++ public/chat.js | 26 +++++++++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 76832ae..fd94de2 100644 --- a/index.js +++ b/index.js @@ -25,4 +25,8 @@ io.on('connection', function(socket){ socket.on('typing', function(data){ socket.broadcast.emit('typing', data); }); + + socket.on('stop-typing', function(data) { + socket.broadcast.emit('stop-typing', data); + }); }); \ No newline at end of file diff --git a/public/chat.js b/public/chat.js index 5ca07b8..0e68834 100644 --- a/public/chat.js +++ b/public/chat.js @@ -8,6 +8,8 @@ var message = document.getElementById('message'), output = document.getElementById('output'), feedback = document.getElementById('feedback'); +var currentTimer = undefined; + // Emit events (upon click, emit to chat the message and handle) btn.addEventListener('click', function(){ socket.emit('chat', { @@ -18,9 +20,14 @@ btn.addEventListener('click', function(){ }); // Attach event listener to message input field -message.addEventListener('keypress', function(){ +message.addEventListener('keypress', function() { + if(currentTimer) { + clearTimeout(currentTimer); + } + + currentTimer = setTimeout(emitStopTyping, 1000); socket.emit('typing', handle.value); -}) +}); // Listen for events socket.on('chat', function(data){ @@ -28,6 +35,19 @@ socket.on('chat', function(data){ output.innerHTML += '

' + data.handle + ': ' + data.message + '

'; }); +message.addEventListener('focusout', function(e) { + emitStopTyping(); +}); + socket.on('typing', function(data){ feedback.innerHTML = '

' + data + ' is typing a message...

'; -}); \ No newline at end of file +}); + + +socket.on('stop-typing', function(data) { + feedback.innerHTML = ''; +}); + +function emitStopTyping() { + socket.emit('stop-typing', null); +}