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:
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.
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.