I have an indicator that notifies users when another user is typing by looking for a keypress on an input box. However, if the user removes what they were typing, the indicator still shows other users that they're still typing. How can I alter this to remove the indicator when the input field is empty.
The indicator will disappear when the message is sent, by setting istyping
to an empty string. I'm not sure how to utilise this to detect an empty input field.
var message = document.getElementById('messagebox');
var istyping = document.getElementById('istyping');
message.addEventListener('keypress', function(){
socket.emit('typing', {
user: user || 'Anonymous'
})
})
socket.on('typing', function(data){
istyping.innerHTML = '<p><i>'+ data.user +" is typing..."+'</p></i>';
})
You can use setTimeout() to do it.
Example:
var message = document.getElementById('messagebox');
var istyping = document.getElementById('istyping');
var timeout = setTimeout(function(){}, 0);
message.addEventListener('keypress', function(){
clearTimeout(timeout); /// clear timeout if user is typing
istyping.innerHTML = 'User is typing';
timeout = setTimeout(function()
{ istyping.innerHTML = '' }, 1000 /// Time in milliseconds
)}
)
This basically says that an user is not typing if a key isn't pressed after X milliseconds. You can check out it working here
You can use setTimeout for this. As soon as the user inputs any character in the input field set a new timeout and clear the older one. You can set the time as per your preference.
var message = document.getElementById('messagebox');
var istyping = document.getElementById('istyping');
var typingInterval = 3000;
var typingTimer;
message.addEventListener('keypress', function(){
clearInterval(typingTimer);
typingTimer = setTimeout(doneTyping, typingInterval)
socket.emit('typing', {
user: user || 'Anonymous'
})
})
function doneTyping () {
socket.emit('doneTyping',{
user: user || 'Anonymous'
})
}
socket.on('typing', function(data){
istyping.innerHTML = '<p><i>'+ data.user +" is typing..."+'</p></i>';
})
socket.on('doneTyping', function(data){
istyping.innerHTML = '';
})
This solution will remove the is Typing... text from UI if user does not type anything for 3 seconds
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.