How to trigger an event in input text after I stop typing/writing

How to trigger an event in input text after I stop typing/writing

Sometimes we need to trigger a subsequent function when performing some task. In this post, we will explain to you how you can trigger callback in jQuery after the user stops typing.

The callback is used in many ways like we use callback function in AJAX call, autosave something, etc. In the below code snippet, we have given a textarea. When you stop after writing something then the callback function triggered automatically and alert you the message. In application, you can perform some other activity instead of alert.

This is a useful code that you can use to trigger a call backup function such as autosave, ajax request, spelling check, or something else as per requirements.

//HTML
<textarea id="input-box"></textarea>

jQuery code to Trigger callback after the user stops typing.

var x_timer;    
$("#input-box").keyup(function (e){
    clearTimeout(x_timer);
    var user_name = $(this).val();
    x_timer = setTimeout(function(){
       // callback_function();
       console.log("user stopped");
    }, 1000);
});

Complete Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to trigger an event in input text after I stop typing/writing</title>
</head>
<body>
<textarea id="input"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var x_timer;    
$("#input").keyup(function (e){
    clearTimeout(x_timer);
    var user_name = $(this).val();
    x_timer = setTimeout(function(){
       // callback_function();
       console.log("user stopped");
       alert('user stopped');
    }, 1000);
});
</script>
</body>
</html>

You can also check Restrict multiple URLs or Email id in the Input field with jQuery validation.

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *