Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Tip to Detect Key Press through JavaScript and jQuery

0.00/5 (No votes)
15 Oct 2014 1  
Detect type of key press through JavaScript and jQuery

Introduction

Sometimes, we are in a situation when we are required to find out which key is pressed through code. Below is the sample code for getting key press using client side script (JavaScript and jQuery):

Using JavaScript

<script type="text/javascript">

    document.onkeydown = testKeyEvent;
    document.onkeypress = testKeyEvent
    document.onkeyup = testKeyEvent;

    function testKeyEvent(e) {

        if (e.keyCode == 13) //We are using Enter key press event for test purpose.
        {
            alert('Enter key pressed');

        }
        else //If any other button pressed.
        {
            alert('Not Enter key pressed');
        }
    }

   </script>

Using jQuery

<script>

    $(function () {
        $(document).on('keyup keydown keypress', function (event) {
            if (event.keyCode == 13) {
                alert("Enter key pressed");
            }
            else {
                alert("Not Enter key pressed");
            }

        });
    });

   </script>

Use the above code and play with key press. :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here