Languages
[Edit]
EN

JavaScript - onkeydown event example

0 points
Created by:
Wayne
475

In this article, we would like to show you onkeydown event example in JavaScript.

Quick solution:

var myElement = document.querySelector('#my-element');

myElement.addEventListener('keydown', function() {
    console.log('onkeydown event occurred.');
});

or:

<input type="text" onkeydown="handleKeydown()">

or:

var myElement = document.querySelector('#my-element');

myElement.onkeydown = function() {
    console.log('onkeydown event occurred.');
};

 

Practical examples

There are three common ways how to use onkeydown event:

  • with event listener,
  • with element attribute,
  • with element property.

1. Event listener based example

In this section, we want to show how to use onkeydown event on input element via event listener mechanism.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something: </p>
    <input type="text" id="my-input">
    <script>
      var myInput = document.querySelector('#my-input');

      myInput.addEventListener('keydown', function() {
        console.log('onkeydown event occurred.');
      });
    </script>
  </body>
</html>

2. Attribute based example

In this section, we want to show how to use onkeydown event on input element via attribute.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something: </p>
    <input type="text" onkeydown="handleKeydown()">
    <script>
      function handleKeydown(){
        console.log('onkeydown event occurred.');
      }
    </script>
  </body>
</html>

3. Property based example

In this section, we want to show how to use onkeydown event on input element via property.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Type something: </p>
    <input type="text" id="my-input">
    <script>
      var myInput = document.querySelector('#my-input');

      myInput.onkeydown = function() {
        console.log('onkeydown event occurred.');
      };
    </script>
  </body>
</html>

Alternative titles

  1. JavaScript - keydown event example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - events

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join