Rusfearuth
Rusfearuth

Reputation: 3261

How to create function for jquery .keydown?

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

Upvotes: 1

Views: 1406

Answers (1)

Nick Craver
Nick Craver

Reputation: 630389

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);
  });
});

Upvotes: 4

Related Questions