how to make Javascript keyboard shortcut in all browser
-
06-07-2019 - |
Question
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
Solution
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.
OTHER TIPS
Are you permitted to use jQuery? Because this will work:
$(window).keydown(function(event){
if(event.keyCode == 83){
alert('hello');
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow