jQuery

jQuery Arrow Keys Binding Examples

jQuery Arrow Keys: Have you ever wondered how to bind arrow keys using jQuery? Let’s say that you want to enhance your user experience to a website by using jQuery or you want to trigger an action when certain key, such as the Up arrow key or Down arrow key, etc. is pressed, do you know what code can be used? In this article, I am going to share with you an easy way to bind arrow keys using jQuery with easy to follow examples.

How to use jQuery to Bind Arrow Keys

At one time or the other, you might end up developing an app that requires you to perform a certain action when the arrow keys are hit/pressed. In such a case, you can execute specific code if you can find out which arrow key was hit. There are different key codes for each of the arrow key and we can use this to our advantage. And in order to use this, we will need to bind arrow keys based on their unique codes. Following are the examples to show you how to do this.

Example: Bind Arrow Keys using jQuery

This example has code that monitors for arrow key hit event and then triggers an alert indicating the arrow key that was hit. Simply execute the following code and hit the arrows keys on your keyboard to see the alert message.

<html>
<head>
<title>jQuery Arrow Keys | Bind Arrow Keys using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>

Hit the arrows keys on your keyboard to see the alert!

<script type="text/javascript">

$(document).keydown(function(e){

	//e.which is set by jQuery for those browsers that do not normally support e.keyCode.
	var keyCode = e.keyCode || e.which;

    if (keyCode == 38) 
	{ 
       alert( "Up arrow key hit." );
       return false;
    }

    if (keyCode == 40) 
	{ 
       alert( "Down arrow key hit." );
       return false;
    }

    if (keyCode == 37) 
	{ 
       alert( "Left arrow key hit." );
       return false;
    }

    if (keyCode == 39) 
	{ 
       alert( "Right arrow key hit." );
       return false;
    }

});

</script> 
</body>
</html>
That’s it!

Do you know of any other ways to bind arrow keys using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*