"User is typing" function in chat
Asked Answered
D

5

19

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.

Diagnostic answered 22/1, 2012 at 19:12 Comment(2)
+1 for you ..Did you got the solution ? Because I also need the same thing exactly what you need ?Raceme
Where does someone put the ajax code for sending dataSpook
P
14

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);
Primitive answered 24/4, 2013 at 14:7 Comment(3)
Where does someone put the ajax code for sending dataSpook
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.??Oversubtle
@jamesOduro probably sending the typing data through socket will be a better idea rather than inserting in database.Tarnetgaronne
J
3
     <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>
Jeepers answered 25/2, 2017 at 14:24 Comment(2)
Simple Javascript + HTML is sufficient to get this feature.Jeepers
I found that in my browser onkeypress does not include backspace, delete, arrow keys or shift, (but that's probably not a problem.)Christy
P
3

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.

Pinch answered 4/1, 2018 at 22:45 Comment(0)
Q
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;">
Quianaquibble answered 19/5, 2021 at 18:36 Comment(0)
C
1

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");
    }
});
Cashbook answered 9/5, 2012 at 4:57 Comment(1)
How do we pass this to other chatter? I assume this will show activity of me typing.Diary

© 2022 - 2024 — McMap. All rights reserved.