1

$(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?

1 Answer 1

4

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);
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.