garry towel
garry towel

Reputation: 59

Run the same code when 2 different events occur

I have a big piece of code that's being executed when I click on a div element and I want the same code to be executed when I press the right arrow on the keyboard. I can't find a way to embed one event into the other.

So is it possible all of this code to be written only once and not twice for the different events?

Upvotes: 0

Views: 169

Answers (2)

taylorcressy
taylorcressy

Reputation: 965

Easy. Just bind two event handlers.

$('#myDiv').click(myFunction);
$('#myDiv').keyPress(keyPressHandle);

function myFunction(e) {
    //Your "Big piece of code"
}

function keyPressHandle(e) {
    switch(e.which) {
         case 39: // right
         myFunction(e);
         break;
    }
}

Upvotes: 1

Goose
Goose

Reputation: 4821

use an if statement that uses the "or" expression ||

if (click || keypress) {
do stuff
}

That's the basic syntax. You should be able to apply that to your code. Hope this helps.

Upvotes: 0

Related Questions