user759235 user759235 - 7 months ago 11
Javascript Question

How to get the parameter to work inside a event function

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

Answer

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