Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine keypress & on click function in JavaScript?

I have the following two functions:

$("input").keypress(function(event) {
   if (event.which == 13) {
   //code        
   }       
});

$('#login_submit').click(function () {        
   //code                    
});

The code which is being used in the functions are EXACTLY the same code, basically code dublication. So i was wondering if there is a way to combine these functions with an OR statement??

like image 489
Sino Avatar asked Feb 03 '13 16:02

Sino


People also ask

Should I use Keyup or Keydown?

Both are used as per the need of your program and as per the convenience of the user. keyup Fires when the user releases a key, after the default action of that key has been performed. keydown Fires when the user depresses a key.

What is the difference between keypress () and Keydown ()?

keydown – fires when any key is pressed down, fires first, and always before the browser processes the key (e.g. inserting text, moving focus, etc). keypress – fires when a key that produces a character value is pressed down, fires after keydown , and before the browser processes the key.

What is Keydown and Keyup?

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase "A" is reported as 65 by all events.

Is keypress deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.


1 Answers

Create your own callback and pass that to the event handlers.

var callback = function() {...};

$("input").keypress(function() {
    if (event.which == 13) callback();
});

$('#login_submit').click(callback);
like image 137
David G Avatar answered Sep 18 '22 00:09

David G