Is there a way to make two different functions?

As an example, if I want the user to make clicks and keystrokes that will give the same result. I would not want to have two identical codes.

If I had something like

$('#next').click(function(){ // code goes here }); 

I would also like to implement this

 $(document).keydown(function(e){ if (e.keyCode == 37) { alert( "left pressed" ); return false; } }); 

which will be part of the click. Do you have some ideas? Thanks!

+4
source share
4 answers
 function myFunc() { alert("left pressed"); } $("#next").click(myFunc); $(document).keypress(function(e) { if(e.keyCode == 37) myFunc(); }); 

You can also have myFunc () handle both events, for example ..

 function myFunc(e) { // First we check to see if this event has a keyCode property // If so, then we need to check the value of that keyCode. // If it doesn't match the value we're trying to capture, // then we just "exit" the function by returning false. if(e.keyCode && e.keyCode != 37) { return false; } alert("left pressed"); } // Since myFunc() handles both scenarios, we can // bind it to both objects. $("#next").click(myFunc); $(document).keypress(myFunc); 
+5
source

something like that

 function clicky(e) { e.preventDefault(); console.log('do stuff'); } $('#next').click(clicky); $(document).keydown(clicky); 

you want to write a function and call it later

living example: http://jsfiddle.net/mPhAZ/

+1
source

Wrap the common code in a separate function and call from your selection functions? Or I do not understand your question?

So:

 function doSomeStuff() { // common code here } $('#next').click(function() { doSomeStuff(); }); $(document).keydown(function(e) { if(e.keyCode == 37) { alert("left pressed") ; doSomeStuff(); return false; } }); 
+1
source
 $(document).keydown(function(e){ if (e.keyCode == 37) { $('#next').click(); } }); 

.click () is a standard javascript function that can be used to simulate a button click.

0
source

All Articles