Wednesday, October 12, 2011

jQuery exercise: get key input

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p id="mytext1">Original Text</p>
<p id="mytext2">Wait Key</p>
<p id="mytext3">Wait Key</p>
<script>
$(function(){
var str = "This run after DOM loaded";
$("#mytext1").html(str);

var KEY_UP = 38;
var KEY_DOWN = 40;
var KEY_LEFT = 37;
var KEY_RIGHT = 39;

//Set listener for keydown
$(document).keydown(function(e){
$("#mytext2").html("- keydown -");
switch(e.which){
case KEY_UP:
$("#mytext3").html("Key: UP");
break;
case KEY_DOWN:
$("#mytext3").html("Key: DOWN");
break;
case KEY_LEFT:
$("#mytext3").html("Key: LEFT");
break;
case KEY_RIGHT:
$("#mytext3").html("Key: RIGHT");
break;
}
});

//Set listener for keyup
$(document).keyup(function(e){
$("#mytext2").html("Wait Key");
$("#mytext3").html("Wait Key");
});

});
</script>
</body>
</html>


jQuery exercise: get key input



No comments:

Post a Comment