<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="puck"></div>
</div>
// Add your event handler here to listen for keyboard
// activity and call the functions below as needed.
window.addEventListener('keydown', keydown);
// initial location of the puck, and step size
var step = 4;
var top = 90;
var left = 190;
// utility functions that will move the puck
var puck = document.getElementById("puck");
function mvup(){
top -= step;
puck.style.top = top + "px";
}
function mvdown(){
top += step;
puck.style.top = top + "px";
}
function mvleft(){
left -= step;
puck.style.left = left + "px";
}
function mvright(){
left += step;
puck.style.left = left + "px";
}
function keydown(e) {
if (e.which == 37) {
mvleft();
} else {
if (e.which == 38) {
mvup();
} else {
if (e.which == 39) {
mvright();
} else {
if (e.which == 40) {
mvdown();
}
}
}
}
}
//console.log(e.which);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.