Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery : Event on click or keydown without redundancies?

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

like image 654
halpsb Avatar asked Jan 14 '23 03:01

halpsb


1 Answers

.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);
like image 89
MrCode Avatar answered Jan 31 '23 06:01

MrCode