Click here to Skip to main content
15,887,214 members
Articles / Programming Languages / Javascript
Tip/Trick

Tip to Detect Key Press through JavaScript and jQuery

Rate me:
Please Sign up or sign in to vote.
4.50/5 (6 votes)
15 Oct 2014CPOL 17.8K   9   2
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

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

JavaScript
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSimple way of capturing keyboard events on entire page Pin
Member 1079431316-Oct-14 8:26
Member 1079431316-Oct-14 8:26 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun15-Oct-14 21:37
Humayun Kabir Mamun15-Oct-14 21:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.