Practice Set, Week 9, Keyboard Events
by mtzara
HTML
<h3>Practice Set, Week 9, Keyboard Events</h3>
<p>This page contains a box with a "puck" in it. The javascript contains functions that will move the puck in each of four directions. Your task is to write an event handler that will respond to the keyboard - specifically, to allow the user to use the arrow keys to move the puck around.</p>
<p>You can attach an event handler to the window object, and have a conditional to see which key was pressed. The <a href="http://jsfiddle.net/cscie3/j1uLsvay/">keyCode utility</a> we referred to in Week 9, lesson 3 of the course may be helpful to you.</p>
<p>Also, when running your code in JSFiddle, you will have to give this HTML output frame focus (by clicking on it once) for your code to capture keyboard activity. </p>
<p>Hint - all you have to do is listen for keydown or keyup, and depending on which arrow key was pressed, call the appropriate function. </p>
<div id="container">
<div id="output"></div>
<div id="puck1"></div>
<div id="puck2"></div>
<div id="puck3"></div>
</div>
<div>
<button type="button">Scramble!</button>
</div>
CSS
#container{
height: 200px;
width: 400px;
border: 1px solid black;
background-color: #dddddd;
}
#puck1{
border: 1px solid red;
height: 20px;
width: 20px;
background-color: red;
position:relative;
top: 90px;
left: 190px;
}
#puck2{
border: 1px solid yellow;
height: 20px;
width: 20px;
background-color: yellow;
position:relative;
top: 90px;
left: 190px;
}
#puck3{
border: 1px solid green;
height: 20px;
width: 20px;
background-color: green;
position:relative;
top: 90px;
left: 190px;
}
JavaScript
// Add your event handler here to listen for keyboard
// activity and call the functions below as needed.
window.addEventListener("keydown", handleKeyPress, false);
function handleKeyPress (evt) {
if(evt.which == 37 || evt.keyCode == 37){
mvleft();
}
else if(evt.which == 39 || evt.keyCode == 39){
mvright();
}
else if(evt.which == 38 || evt.keyCode == 38){
mvup();
}
else if(evt.which == 40 || evt.keyCode == 40){
mvdown();
}
}
// initial location of the puck, and step size
var step = 4;
var pTop = 90;
var pLeft = 190;
// utility functions that will move the puck
var puck1 = document.getElementById("puck1");
var puck2 = document.getElementById("puck2");
var puck3 = document.getElementById("puck3");
function mvup(){
pTop -= step;
puck.style.top = pTop + "px";
}
function mvdown(){
pTop += step;
puck.style.top = pTop + "px";
}
function mvleft(){
pLeft -= step;
puck.style.left = pLeft + "px";
}
function mvright(){
pLeft += step;
puck.style.left = pLeft + "px";
}
function init(){
puck1 = document.getElementByID("puck1");
spaceW=screen.height-picture.height;
spaceH = screen.width - picture.width;
setInterval(scramble, 500);}
button.onclick = function scramble () {
puck1.style.top = math.round(math.random() * spaceW) + "px";
puck1.style.left = math.round(math.random() * spaceH) + "px";
}