65.9K
CodeProject is changing. Read more.
Home

Tip to Detect Key Press through JavaScript and jQuery

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (6 votes)

Oct 15, 2014

CPOL
viewsIcon

18114

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. :)