user13863639
user13863639

Reputation:

ctrlKey event in Javascript

I am trying to catch the "ctrl + f" event in Javascript. Even though, any letter on my keyboard fires an event, "ctrl" does not. Could you help me, please?

Below, is the code I execute:

if (event.ctrlKey && event.key === 'f') {
event.preventDefault();
document.querySelector("#search").focus(); 
}

Upvotes: 0

Views: 1338

Answers (1)

m_wer
m_wer

Reputation: 1524

Use the 'onkeydown' event to capture the ctrl event.

<html>
    <head>
      <title>ctrlKey example</title>

      <script type="text/javascript">

      function checkKeyPress(e){

        if (event.ctrlKey ) {
          event.preventDefault();
          alert(
            "CTRL key pressed: " + e.ctrlKey + "\n"
          );
        }
      }

      </script>
    </head>

    <body onkeydown="checkKeyPress(event);">
      <p>Press CTRL</p>
    </body>
</html>

Upvotes: 2

Related Questions