Capturing keyup and keydown events
jQuery can watch for keys to be pressed and released, and run code on each.
HTML
Click in this frame, then press a direction key to move.<br>
ESC or ENTER will reset the location.
<div id="displayKey"></div>
CSS
#displayKey {
background-color: #cacaff;
color: #00f;
padding: 5px;
height: 20px;
width: 100px;
text-align: center;
border: 3px outset;
position: absolute;
top: 60px;
left: 10px;
}
body {
margin: 10px;
}
JavaScript
$("#displayKey").html("[" + $("#displayKey").offset().left + ", " + $("#displayKey").offset().top + "]");
$(document).keydown(function (e) {
var keyPressed= e.keyCode || e.which, whichKey= {left: 37, up: 38, right: 39, down: 40, esc: 27, enter:13 };
var moveSpeed = 5;
var currentPos;
switch (keyPressed) {
case whichKey.left:
currentPos = $("#displayKey").offset().left;
$("#displayKey").css("left",currentPos -moveSpeed );
$("#displayKey").html("[" + $("#displayKey").offset().left + ", " + $("#displayKey").offset().top + "]");
break;
case whichKey.up:
currentPos = $("#displayKey").offset().top;
$("#displayKey").css("top",currentPos -moveSpeed );
$("#displayKey").html("[" + $("#displayKey").offset().left + ", " + $("#displayKey").offset().top + "]");
break;
case whichKey.right:
currentPos = $("#displayKey").offset().left;
$("#displayKey").css("left",currentPos + moveSpeed );
$("#displayKey").html("[" + $("#displayKey").offset().left + ", " + $("#displayKey").offset().top + "]");
break;
case whichKey.down:
currentPos = $("#displayKey").offset().top;
$("#displayKey").css("top",currentPos +moveSpeed );
$("#displayKey").html("[" + $("#displayKey").offset().left + ", " + $("#displayKey").offset().top + "]");
break;
case whichKey.esc:
$("#displayKey").html("ESC");
$("#displayKey").css("left","10px");
$("#displayKey").css("top","60px");
break;
case whichKey.enter:
$("#displayKey").html("Enter");
$("#displayKey").css("left","10px");
$("#displayKey").css("top","60px");
break;
}
});
$(document).onkeypress(function (e) {
$("#displayKey").html("[" + $("#displayKey").offset().left + ", " + $("#displayKey").offset().top + "]");
});