"User is typing" function in chat

20,770

Solution 1

I have created a fiddle that might be helpful to you. The idea is to refresh activity message using javascript setInterval function.

var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970, actually some time in the past
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message

function refreshTypingStatus() {
    if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
        typingStatus.html('No one is typing -blank space.');
    } else {
        typingStatus.html('User is typing...');
    }
}
function updateLastTypedTime() {
    lastTypedTime = new Date();
}

setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);

Solution 2

     <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }

        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 



    <!DOCTYPE html>
    <html>
       <head>
       </head>
       <body>

      <script>
        function isTyping() {
                document.getElementById('typing_on').innerHTML = "User is typing...! "; }
            
        function  notTyping (){
       document.getElementById('typing_on').innerHTML = "No one is typing ! "; }
    </script>

    <label>
        <textarea onkeypress="setTimeout(isTyping(),4000); setInterval(notTyping,5000)"  name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div> 
       </body>
    </html>

Solution 3

var isTyping = false;
var isNotTyping;
  document.getElementById('chat-message-input').onkeypress = () => {
  sendIsTypingToUser()
  if (isNotTyping != undefined) clearTimeout(isNotTyping);
  isNotTyping = setTimeout(sendIsNotTyping, 900);
  };

  function sendIsTypingToUser(){
     if(!isTyping){
        console.log("IsTyping...........")
        isTyping = true
        }
     }
  function sendIsNotTyping(){
     console.log("Not Typing...........")
     isTyping = false
     }
<input id="chat-message-input" type="text" placeholder="Enter Message..." autofocus style="width: 50%; padding: 8px;">

Solution 4

Theres a nifty library plugin called underscore.js

Among its many useful functions is one called _.debounce, which can be used like so to track typing:

var typing, typingStarted, typingStopped;

typing = false;

typingStopped = _.debounce((function() {
  if (!typing) {
    return;
  }
  typing = false;
  console.log('typing is done so do what ever you need to do to notify it');
}), 5000);

typingStarted = function() {
  if (this.typing) {
    return;
  }
  typing = true;
  console.log('typing has started so do what ever you need to do to notify it');
};

document.querySelector("textarea").oninput = function(event) {
  typingStarted();
  typingStopped();
  return
};

The way this works is that on input of the text area typingStarted is called and sets typing to true preventing it from being called again. typingStopped is then called, but will only invoke the function wrapped in the _.debounce after 5000 ms which is given as the second argument to _.debounce. However if you call typingStopped again, it will reset the countdown back to 5000 ms from where ever it was at. Since typingStopped is called on each input, it will only ever execute typing = false after a full 5 seconds between key presses.

Solution 5

You can use JQuery to handle the keypress event instead of HTML. You might try something like this. Then set your default #typing on div as User is not typing.

//EXECUTES WHEN KEY IS PRESSED IN SPECIFIED ELEMENT
$("#textarea").keypress(function(){
numMiliseconds = 500;

//THIS IF STATEMENT EXECUTES IF USER CTRL-A DELETES THE TEXT BOX
if ($("textarea") == ""){
    $("#typing_on").text("User has cleared the text box");
}

$("#typing_on").text("User is typing").delay(numMiliseconds).queue(function(){
    $("#typing_on").text("User has stopped typing");
    }
});
Share:
20,770
Ingrid
Author by

Ingrid

Willing to learn...

Updated on July 05, 2022

Comments

  • Ingrid
    Ingrid almost 2 years

    I'm trying to add in chat a "user is typing" function; chat written in PHP + MySQL/Ajax.

    How it should work:

    -when my chat partner X starts typing I see in my chat box: "X is typing"

    -when I (named Y) am typing he sees in his chat box: "Y is typing" (just like Yahoo Messenger).

    The code I've tried so far:

    <script type="text/javascript" language="javascript">
        var timer = 0;
    
        function reduceTimer() {
            timer = timer - 1;
            isTyping(true);
        }
    
        function isTyping(val) {
            if (val == 'true') {
                document.getElementById('typing_on').innerHTML = "User is typing...";
            } else {
    
                if (timer <= 0) {
                    document.getElementById('typing_on').innerHTML = "No one is typing -blank space.";
                } else {
                    setTimeout("reduceTimer();", 500);
                }
            }
        }
    </script>
    
    <label>
        <textarea onkeypress="isTyping('true'); timer=5;" onkeyup="isTyping('false')" name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </label>
    <div id="typing_on">No one is typing -blank speace.</div>
    

    Questions:

    1. If I stop for a few seconds to think about my spelling it looks like I've stopped typing. Is there a more relevant and less complicated way to set this function? Is there possible a code for:

      • text box not empty (user pressed any key so started typing) -> Message: User is typing.
      • text box empty -> Message: User is not typing.
      • text box not empty, but user hasn't pressed any key for longer than 5 seconds -> Message: User is not typing.
    2. It shows to myself that I am typing; how could I implement it or where, in order to see in my chat box the "X user is typing" and not "Myself is typing". Same for the other user, he should get a message about me typing/not typing , not about himself.

    Thank you.

  • Omari Victor Omosa
    Omari Victor Omosa about 8 years
    Where does someone put the ajax code for sending data
  • james Oduro
    james Oduro over 7 years
    This is perfect...but I want to ask if you know how the database will loop like..How do i get the User is typing to the other user if am typing.??
  • Darktwen
    Darktwen over 7 years
    How do we pass this to other chatter? I assume this will show activity of me typing.
  • Sivananda Mandapati
    Sivananda Mandapati over 7 years
    Simple Javascript + HTML is sufficient to get this feature.
  • Alexx Roche
    Alexx Roche over 7 years
    I found that in my browser onkeypress does not include backspace, delete, arrow keys or shift, (but that's probably not a problem.)
  • marukobotto
    marukobotto over 6 years
    @jamesOduro probably sending the typing data through socket will be a better idea rather than inserting in database.