Search code examples
javascriptdom-eventskeyboard-events

Is There a Way to Capture How Long a Key is Pressed Down?


I'm building a small app with React and want to be able to program functionality in which the user holds down a key, and the amount of time the key is pressed down for is captured. I do not want to capture when a button is clicked.

So far I have this:

import { KeyboardEvent } from "react";

const App = () => {
  const handleKeyChange = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "y") alert("yes");

    if (e.key === "n") alert("no");
  };
  return (
    <div className="App">
      <input
        type="text"
        placeholder="Press the 'y' or 'n' key"
        onKeyPress={handleKeyChange}
      />
    </div>
  );
};

export default App;

Solution

  • You can use onKeyDown and onKeyUp events:

        import { KeyboardEvent } from "react";
    
        const App = () => {
          let date;
          const handleKeyDown = (e: React.KeyboardEvent) => {
            date = + new Date()
          };
          const handleKeyUp = (e: React.KeyboardEvent) => {
            const diff = +new Date() - this.date();
            // do whatever you want with the diff
          };
          return (
            <div className="App">
              <input
                type="text"
                onKeyDown={handleKeyDown}
                onKeyUp={handleKeyUp}
              />
            </div>
          );
        };
    
        export default App;