Reputation: 143
<label id="statusLabel">Online</label>
<input type="text" id="txtInput">
<script>
if($('txtInput').keyup()) {
$('#statusLabel').text('typing...');
}
else {
$('#statusLabel').text('online');
}
</script>
I want set statusLabel.text to 'typing' when I'm typing on the keyboard.And statusLabel.text to 'online' when I'm not typing on the keyboard.I have tried this code and It's not working.Is it possible to do so?.Really appreciate if your'll can help.Thanks
Upvotes: 0
Views: 992
Reputation: 143
var timerID;
$('#txt').keyup(function(){
$('#status').text('Typing...');
timerID = setTimeout(clearThis, 1300);
});
function clearThis(){
$('#status').text('online');
clearInterval(timerID);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="status">Online</label>
<br>
<input type="text" id="txt">
Upvotes: 0
Reputation: 1195
var timer = null;
$('#txtInput').keydown(() => {
$('#statusLabel').text('Typing...');
clearTimeout(timer);
timer = setTimeout(() => $('#statusLabel').text('Online'), 1000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="statusLabel">Online</label>
<input type="text" id="txtInput">
Upvotes: 1
Reputation: 27051
I would do something like this:
var typing;
var interval = 500;
//on keyup, start the countdown
$('#txtInput').keyup(function() {
$('#statusLabel').text('typing...');
clearTimeout(typing);
if ($('#txtInput').val()) {
typing = setTimeout(doneTyping, interval);
}
});
function doneTyping() {
$('#statusLabel').text('online')
}
Here I use setTimeout
and clearTimeout
so the text dont flash between typing...
and online
.
Basic, what it does is that when you start typing, it changes the text, and clears the timer. If you press another key within 0,5 seconds then it will clear the timer once more.
Once you haven't typed anything for 0,5 sec then it will change the text of statusLabel
Demo
var typing;
var interval = 500;
//on keyup, start the countdown
$('#txtInput').keyup(function() {
$('#statusLabel').text('typing...');
clearTimeout(typing);
if ($('#txtInput').val()) {
typing = setTimeout(doneTyping, interval);
}
});
function doneTyping() {
$('#statusLabel').text('online')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="statusLabel">Online</label>
<input type="text" id="txtInput">
Upvotes: 0
Reputation: 51
this might help you when user start typing then it will show 'typing...' by default after certain time it will show 'online' :
$('txtInput').keyup(function(){
$('#statusLabel').text('typing...');
function timer(){
$('#statusLabel').text('online');
}
//setTimeout(myFunc,5000);
setTimeout(timer,3000);
});
Upvotes: 0