Run Function After User Has Stopped Typing
I have an input field in which user can input a long value. This value is then used as input value in a complex time consuming function. My question is: how can I start execution o
Solution 1:
Here's a rough draft : http://jsfiddle.net/jomanlk/msmJp/
Uses setTimeout
and clearTimeout
var timer = null;
$('#text').keyup(function(){
clearTimeout(timer);
timer = setTimeout(doStuff, 1000)
});
functiondoStuff() {
alert('do stuff');
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><inputtype='text'id='text'>
Solution 2:
This is really late, I know, but I really disliked the lines of code needed to achieve this every time it was needed, so I extracted the logic into a page initiation function that only runs once.
(function(){
var keystoppedTimer = null;
var keystoppedInputs = document.getElementsByTagName('input');
for (var i = 0, l = keystoppedInputs.length; i < l; i++) {
keystoppedInputs[i].addEventListener('keydown', function(event){
clearTimeout(keystoppedTimer);
keystoppedTimer = setTimeout(function() {
event.target.dispatchEvent( newEvent('keystopped') );
}, 600);
}, false);
}
}());
Adding this (think of it as a polyfill), allows for much simpler usage. All you need to do to target the user stopping typing is add an event listener to your element targeting 'keystopped'.
inputElement.addEventListener('keystopped', function(event){
console.log('Stopped typing');
}, false);
I picked keystopped
because it matches keydown
, keyup
, etc.
Solution 3:
Use the bindWithDelay jQuery plugin:
element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)
Solution 4:
I have posted a solution when it ll show user is typing and user stopped type
functiontypingAction(){
$('#typing').text("user is typing....");
clearTimeout();
setTimeout(()=>{
$('#typing').text(' user stopped typing.....'); //**can call your function here**
},2000);
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!DOCTYPE html><html><head><metacharset="utf-8"><title>Chat | ChatApp</title><metaname="viewport"content="width=device-width, initial-scale=1, user-scalable=no"><linkrel="stylesheet"href="/css/styles.css"></head><body ><pid="typing"></p><inputname="message"type="text"placeholder="Message"autofocusautocomplete="off"oninput="typingAction()" /></body></html>
Post a Comment for "Run Function After User Has Stopped Typing"