Question

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

Was it helpful?

Solution

.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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top