Reputation: 2207
As I want to unbind(off) the events I wrapped the code inside a function but as I need to see which key is pressed I need to get the event of the event(not sure how this is called.
// normal example
$('body').on('keydown',function( event ){
if(event.keyCode == 37){
// do something
}
});
// my example
function keyDownHandler() {
if(event.keyCode == 39) {
// does not work
}
}
$('body').on('keydown', keyDownHandler);
Upvotes: 2
Views: 46
Reputation: 2824
$(document).ready(function () {
//1st way
$('body').on('keydown', function(event){
keyDownHandler(event);
});
//2nd way ,same as first but shorter use it for send event only
$('body').on('keydown', keyDownHandler);
//3rd way ,this way to send more data
$('body').on('keydown', {example:'hello world'},keyDownHandler2);
});
function keyDownHandler(event) {
console.log(event.keyCode);
}
function keyDownHandler2(event) {
console.log(event.keyCode);
console.log(event.data.example);
}
Upvotes: 0
Reputation: 115272
You need to get the event object, you can get it as callback function argument
function keyDownHandler(event) {
// set it here ----^^^^^^---
if(event.keyCode == 39) {
// works now
}
}
$('body').on('keydown', keyDownHandler);
Upvotes: 6