Created
July 11, 2012 18:27
-
-
Save hcmn/3092188 to your computer and use it in GitHub Desktop.
Recognize keypresses with Javascript & JQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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