简体   繁体   中英

how to make Javascript keyboard shortcut in all browser

I'm trying to make shortcut with javascript. It works with FF but not with IE8. I'm using this code -

document.onkeydown=function(e)
{ 

if(e.which == 83) 

{ alert("hello"); } 
}

Please give me a simple code which will support all browsers. Thanks

In order to make your code cross-browser, you should:

document.onkeydown = function(e) { 
  e = e || window.event;
  var keyCode = e.keyCode || e.which;

  if(keyCode == 83) { alert("hello"); }
}

Check the above snippet here .

Are you permitted to use jQuery? Because this will work:

$(window).keydown(function(event){
     if(event.keyCode == 83){
          alert('hello');
     } 
});

Partially boosted from here

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