views:

41

answers:

1

I have an <input> which has an onkeydown inline event handler. In this handler, I'd like to call a function and pass a special parameter to it - the event data.

When I want to handle events (e.g. onmousemove) for the whole document, I use the following code:

document.onmousemove=function(e) {
// here I can make a good use of the 'e' variable,
// for example extract the mouse coordinates from it
}

And it works (although I don't know where does the e variable - event data - come from).
But this time I want to use the function only for the input I mentioned in the first sentence.
I need to pass the event data to the function so it can get the pressed key's code. And I want to do it in that inline event handler. I've created a function:

function myfunc (e) {
    var evt=window.event?event:e;
    var code=evt.keyCode;
    alert (code);
}

and tried all of these methods:

<input onkeydown="myfunc(this)">

<input onkeydown="myfunc(this.onkeydown)">

<input onkeydown="myfunc(onkeydown)">

But none of them worked, the alert window displayed just "undefined".
I've looked for a solution to my problem in Google, but didn't find anything that could help me solve it.
Please help me. I just want to know, how to pass the event data in the inline handlers.

+2  A: 

<input onkeydown="myfunc(event)">

function myfunc (e) {
    e = e || window.event;
    var code = e.keyCode;
    alert (code);
}
galambalazs
Thank you really much :) I didn't know about the global `event` variable. Now it works perfectly, thanks again.
rhino
well you should really read a paper before you get into javascript event handling because it can get messy especially if you deal with IE. Anyway, I'm glad I could help.
galambalazs