Reputation: 604
I'm sorry if this is basic, but I've searched and found nothing that works.
I want to load a web page. When that page loads, it displays an image. I want to have the page automatically start listening for a right arrow key press. When that happens, a function in my script will change the image (that part I have gotten to work by using a button that reacts when clicked).
It's the listening for and reacting to a key press I cannot get to work. Note that I'm using Safari, but I would like if possible for it to work in firefox or IE as well.
Please help thanks.
UPDATE TO RESPOND TO COMMENT: Here is what I tried, though I simplified the other part to make this shorter -- now it just writes a result to a div:
<html>
<head>
<script language="Javascript">
function reactKey(evt) {
if(evt.keyCode==40) {
document.getElementById('output').innerHTML='it worked';
}
}
</script>
</head>
<body onLoad="document.onkeypress = reactKey();">
<div id="output"></div>
</body>
</html>
Upvotes: 3
Views: 7640
Reputation: 4072
document.onkeydown= function(key){ reactKey(key); }
function reactKey(evt) {
if(evt.keyCode== 40) {
alert('worked');
}
}
Upvotes: 3
Reputation: 64700
Easiest thing to do is use one of the many many many hotkey libraries, like https://github.com/jeresig/jquery.hotkeys or https://github.com/marquete/kibo.
EDIT: try something like this (after you've already loaded Kibo's javascript).
In your body statement, add the onload
handler: <body onload="setuphandler">
.
Then add something like this (taken from the Kibo page):
<script type="text/javascript">
var k = new Kibo();
function setuphandler()
{
k.down(['up', 'down'], function() {
alert("Keypress");
console.log('up or down arrow key pressed');
});
}
</script>
Upvotes: 1
Reputation: 2202
If you are using jquery, you can do this:
$(document).keydown(function(e){
if (e.keyCode == 39) {
alert( "right arrow pressed" );
return false;
}
});
Upvotes: 3