Skip to content

Instantly share code, notes, and snippets.

@hcmn
Created July 11, 2012 18:27
Show Gist options
  • Save hcmn/3092188 to your computer and use it in GitHub Desktop.
Save hcmn/3092188 to your computer and use it in GitHub Desktop.
Recognize keypresses with Javascript & JQuery
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div id ="a"></div>
<div id = "s"></div>
<div id = "d"></div>
<div id="f"></div>
</body>
</html>
//page needs to be in focus before the following will work.
//slideToggle() automates slideUp() & slideDown()
//credit: Benjamin Clifford, Codecademy
$(document).ready(function(){
$(document).keypress(function(event){
//get string of key pressed for easier comparison than keycodes
var keyPressed = String.fromCharCode(event.keyCode);
//attach a handler to the appropriate div.
var $divs = $("div");
switch (keyPressed) {
case "a":
$divs.eq(0).slideToggle();
break;
case "s":
$divs.eq(1).slideToggle();
break;
case "d":
$divs.eq(2).slideToggle();
break;
case "f":
$divs.eq(3).slideToggle();
break;
}
});
});
div{
width: 50px;
height: 50px;
}
#a {
background-color: #EE0000;
}
#s {
background-color: #00EE00;
}
#d {
background-color: #EEEE00;
}
#f {
background-color: #0000EE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment