Uday A. Navapara
Uday A. Navapara

Reputation: 1265

same function for Mouse Click and Key Press

I want to call a function in jquery when mouse click or key press is occure

one way is to write same code twice for this both event but it is not proper way

can any one tell me how it is possible?

Upvotes: 0

Views: 2721

Answers (7)

Ash
Ash

Reputation: 1422

You also use :

$( "input" ).on('keypress mouseup',function() {

 alert('done');

});

or

$( "input" ).on('keypress mouseup',fun);

Upvotes: 0

AK47
AK47

Reputation: 3807

Write only one function & call it on both event.

$( "#target" ).keypress(function() {

funABC(); });

    $( "#target" ).click(function() {

funABC(); });

function funABC(){alert("DONE");}

One more shortcut :

    $( "#target" ).click(function() {
  $( "#target" ).keypress();
});


   $( "#target" ).keypress(function() {
funABC();
});

Upvotes: 1

prakashrajansakthivel
prakashrajansakthivel

Reputation: 2042

write a function

function Process(){
//Put all your logic
}

call the function in all the event 

$("some element selector").on("click keypress",function() {
     Process();
});

or any other click event.

Upvotes: 2

Humpty Dumpty
Humpty Dumpty

Reputation: 57

Try this:-

$(element).on('click keypress keydown', function() {

});

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

yes you can use like

<input type="text"  />


$(document).on("click mouseenter","input",function(){});

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22415

Use the on method.

$("some element selector").on("click keypress",function() {
     //do something
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

If you want to register both handlers to the same element then you can use .on() to register handler for multiple events

$('myelementselector').on('click keypress', function () {
    //mycode
})

Upvotes: 1

Related Questions