jquery on arrow key code example

Example 1: jQuery Arrow Keys Binding Examples

<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>

Example 2: jquery left arrow key press

$("body").keydown(function(e) {
  if(e.keyCode == 37) { // left
    $("#showroom").animate({
      left: "-=980"
    });
  }
  else if(e.keyCode == 39) { // right
    $("#showroom").animate({
      left: "+=980"
    });
  }
});

Tags:

Html Example