JQuery : Event on click or keydown without redundancies?

halpsb picture halpsb · Jun 13, 2013 · Viewed 10k times · Source

What is the best way to do the same action if either a key press or a click is registered ? I would like to avoid having redundancies and make the code shorter.

Thank you

Answer

MrCode picture MrCode · Jun 13, 2013

.on() can take multiple event names separated by a space, and it will run the same handler for all:

$('#something').on('keypress click', function() {
    // run the same code
});

If you need more flexibility, for example with different conditions then you can create a function:

function myProcedure(e){
    if(e.type == "keydown"){
        console.log(e.keyCode);
    } elseif(e.type == "click"){
        console.log("clicked");
    }
}

$('.leftPlayer').click(myProcedure);
$('body').keydown(myProcedure);