7

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

halpsb
  • 1,106
  • 2
  • 18
  • 28
  • what code have you so far? – Alex Jun 13 '13 at 10:35
  • Basically, at the moment, this is what I have: `$('.leftPlayer').click(function() {...});` `$("body").keydown(function(e) { if (e.keyCode === 37) {...}; }); ` – halpsb Jun 13 '13 at 10:42

1 Answers1

10

.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);
MrCode
  • 63,975
  • 10
  • 90
  • 112