简体   繁体   中英

respond to key press javascript

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>

If you are using jquery, you can do this:

$(document).keydown(function(e){
    if (e.keyCode == 39) { 
       alert( "right arrow pressed" );
       return false;
    }
});

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>
document.onkeydown= function(key){ reactKey(key); }

function reactKey(evt) {
   if(evt.keyCode== 40) {
      alert('worked');
   }
}

http://jsfiddle.net/dY9bT/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM