Reputation: 921
I want to take key press event, ut this is not on specific field, its on page/window.
Example:
While doing automation, on web page I have short-cut key suppose M (keyboard key). So how should I achieve this? If it can be achieved by inserting a JavaScript then how can I write it? I'm beginner in JavaScript.
Upvotes: 0
Views: 123
Reputation: 4620
As you want it on the window I would add a eventListener
function direct on the window object like this. You can google the keyCode if you want to change keyCode. This works with and without jQuery library :) http://jsfiddle.net
window.addEventListener('keypress', function(e) {
e = e || window.event;
switch(e.which) {
case 77:
if (e.ctrlKey) {
alert( "M + ctrlKey is down" );
// do some here
}
else {
alert("M is down")
}
break;
}
}, false);
Upvotes: 0
Reputation: 1251
Try the following code:
<script>
function keyEvent (e) {
if (!e)
e = window.event;
if (e.which) {
keycode = e.which;
} else if (e.keyCode) {
keycode = e.keyCode;
}
if(keycode == 77){
alert('Hi!');
}
}
document.onkeydown = keyEvent;
</script>
Upvotes: 0
Reputation: 1577
Using jquery you can do this as follow.
$(document).keydown(function(e){
if (e.keyCode == 77) {
alert( "M key pressed" );
}
});
Upvotes: 1