Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - Typing status when input field is typed in

I'm trying to make a status popup upon typing. It's like when you are typing in the message input bar to another person with any social media app, it alerts the user to know the other end is responding back to you.

This is basically an example of what I'm trying to achieve.

enter image description here

Here is an attempt but does not work at all how I would like it to. It currently detects as soon as the user inputs text into the input, but does not disappear when the user has sent the message (which clears the input) I've also attempted to hide the div in a function when the message was sent, but that did not work either. Here is my current attempt:

$(document).ready(function(){
    $("#msg").on("input", function(){
        document.getElementById("typing").innerHTML = "Typing...";
    });
});
<span id="typing"></span>

<form id="chat-form">
<input id="msg" type="text" autocomplete="off"/>
question from:https://stackoverflow.com/questions/65901241/typing-status-when-input-field-is-typed-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need to start a timer and remove the text after a certain amount of time. Here's an updated version of your code that works:

$(document).ready(function(){
  var tmo = null;
  $("#msg").on("input", function(){
    document.getElementById("typing").innerHTML = "Typing...";
    
    if (tmo) {
      clearTimeout(tmo);
    }
    tmo = setTimeout(function () {
      document.getElementById("typing").innerHTML = "";
    }, 1000);
    
  });  
});

I created a code pen with a working solution: https://codepen.io/familjenpersson/pen/YzGmWOv


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...