views:

378

answers:

2

So I'm currently trying to make a GreaseMonkey script that will allow a user to press left or right on their keyboard and have that go to a previous comic strip or go to the next strip. I currently have some code up but it's not giving me any results.

function KeyCheck()
{
var KeyID = event.keyCode;
alert(KeyID);
}

document.onKeyDown = KeyCheck();

The code is just for debugging to see if it's actually executing but when I press a key nothing will happen on the page. I'm testing in Firefox also.

+2  A: 

You shouldn't have the () after KeyCheck. Your current code runs KeyCheck and then attempts to set document.onKeyDown to the value returned. If you do it without the () it should instead set the function called KeyCheck to be run on the event.

Also, I think onKeyDown should be all lower case - it's document.onkeydown.

Further example, with an inline function:

document.onkeydown = function() { alert("key down") }

works whereas

document.onkeydown = alert("key down");

doesn't.

PimTerry
A: 

So after Googling for a good 30 minutes, I found out GreaseMonkey doesn't support onkeydown out of the box. I had to use a function called "addEventListener". My final code returns the keyCode of a key pressed on the site properly:

function KeyCheck(e)
{
alert(e.keyCode);
}

window.addEventListener('keydown', KeyCheck, true);
NessDan