tags:

views:

35

answers:

1

Hi! I have this:

$(document).ready(function()
{
    var test_func=function(ev)
    {
        alert(ev.keyCode);
    };
     ....
    $(document).keydown(test_func(ev));
});

I wanna do the next, if I press somebutton on keyboard, I'll see alert with a code of key which I pressed. But I see only 'ev is not defined' in my firebug =|

What do you think about this?

+3  A: 

It should look like this (no parameters in the call):

$(document).keydown(test_func);

The event will be passed as the first argument, and you can use ev.which since jquery normalizes this across browsers :)

When you call a function like this you want to pass the function itself as what to call when the event happens, so use method. If you use method(something) it's trying to invoke the method right then (with a variable ev, that it can't find) and assign the result of that method as the event handler, rather than the method itself.

You could also use an anonymous method, like this:

$(function() {
  $(document).keydown(function(e) {
    alert(e.which);
  });
});
Nick Craver
Many thanks! =)I use usual anonymous method, but now... Now I have a special task =) I've got two html objects which use the same method, that's way I created a one for two objects.
Rusfearuth