简体   繁体   中英

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?

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.

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();
});

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
})

Use the on method.

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

yes you can use like

<input type="text"  />


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

Try this:-

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

});

You also use :

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

 alert('done');

});

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM